问:
How can i convert a file .png to a Bitmap? Nothing works for me. Error "'Failed to decode image. The provided image must be a Bitmap.'" Xamarin.forms
I'm working with Xamarin in the part of  Xamarin.Forms  i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:

1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"

2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.

3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.

4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information  about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).

5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.

the "image.png" i have to save in a string variable, well that's the idea.

If you have a solution with SkiaSharp o whatever i will glad

EDIT

here is a part of my code, i just save in a variable the image

```<code>Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen
</code>```

EDIT 2 This is my method to show the pins in google maps

```<code>private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
        {
            if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
            {
                var location = Geolocation.GetLastKnownLocationAsync();
                PointsOfInterest position = new PointsOfInterest();
                if (location != null)
                {
                    position.ccsm0166latitud = location.Result.Latitude;
                   position.ccsm0166longitud = location.Result.Longitude;

            }
            else {
                position = resultPointsOfInterest.First();
            }
            //Distance = Distance.FromKilometers(new Random().Next(23,35));
            Distance = Distance.FromKilometers(3);
            Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
            PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
                x => new PinCustom()
                {
                    Position =
                        new Position(x.ccsm0166latitud, x.ccsm0166longitud),
                    Address = x.ccsm0166direccion,
                    Label = x.ccsm0166nombre,
                    Type = PinType.Place,
                    TypePointOfInterest = x.ccsm0166tipositio,
                    IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ?  PinCustom.ConvertToBitmap("pin_blue.png") :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
                }).ToList());
        }
        else
        {
            Pins = new List<PinCustom>();
        }
    }
</code>```

This is the class Pin where i save the image

```<code>public class PinCustom : Pin
    {
        public string TypePointOfInterest { get; set; }
        public string Icon { get; set; }
        public Bitmap { get; set; }
        //Here  i create this variable to save a bitmap but i don't know if i do the things well
    }
</code>```

this is the icon .png i want to show in googlemaps

Pin Blue Image

答:
To open your file and convert it to byte array:

```<code>string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
// or your image directory, just replace it
var stream = File.OpenWrite(Path.Combine(directory, "image.png"));
byte[] buff = ConvertStreamToByteArray(stream);
stream.Close();

public static byte[] ConvertStreamToByteArray(Stream stream)
        {
            byte[] byteArray = new byte[16 * 1024];
            using (MemoryStream mStream = new MemoryStream())
            {
                int bit;
                while ((bit = stream.Read(byteArray, 0, byteArray.Length)) > 0)
                {
                    mStream.Write(byteArray, 0, bit);
                }
                return mStream.ToArray();
            }
        }
</code>```

then, to pass this byte array to SKBitmap:

```<code>SKBitmap bmp = SKBitmap.Decode(buff);
</code>```

EDIT:

If you want to try without ConvertStreamToByteArray():

```<code>byte[] buff = null;
stream.Write(buff, 0, buff.Length);
</code>```

This Write will depend of the type of your stream. In this example, I'm using FileStream.

EDIT 2:

```<code>string resourceID = "image.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;

using (Stream stream = assembly.GetManifestResourceStream(resourceID))
{
   resourceBitmap = SKBitmap.Decode(stream);
   SKBitmap bmp = SKImage.FromBitmap(resourceBitmap);
}
</code>```

and then you can use this bitmap to draw and fill your SKCanvas:

```<code>canvas.DrawBitmap(bmp, 0, 0);
</code>```

Body:
I'm working with Xamarin in the part of  Xamarin.Forms  i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:

1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"

2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.

3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.

4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information  about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).

5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.

the "image.png" i have to save in a string variable, well that's the idea.

If you have a solution with SkiaSharp o whatever i will glad

EDIT

here is a part of my code, i just save in a variable the image

Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen

EDIT 2 This is my method to show the pins in google maps

private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
        {
            if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
            {
                var location = Geolocation.GetLastKnownLocationAsync();
                PointsOfInterest position = new PointsOfInterest();
                if (location != null)
                {
                    position.ccsm0166latitud = location.Result.Latitude;
                   position.ccsm0166longitud = location.Result.Longitude;

            }
            else {
                position = resultPointsOfInterest.First();
            }
            //Distance = Distance.FromKilometers(new Random().Next(23,35));
            Distance = Distance.FromKilometers(3);
            Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
            PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
                x => new PinCustom()
                {
                    Position =
                        new Position(x.ccsm0166latitud, x.ccsm0166longitud),
                    Address = x.ccsm0166direccion,
                    Label = x.ccsm0166nombre,
                    Type = PinType.Place,
                    TypePointOfInterest = x.ccsm0166tipositio,
                    IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ?  PinCustom.ConvertToBitmap("pin_blue.png") :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
                }).ToList());
        }
        else
        {
            Pins = new List<PinCustom>();
        }
    }

This is the class Pin where i save the image

public class PinCustom : Pin
    {
        public string TypePointOfInterest { get; set; }
        public string Icon { get; set; }
        public Bitmap { get; set; }
        //Here  i create this variable to save a bitmap but i don't know if i do the things well
    }

this is the icon .png i want to show in googlemaps

Pin Blue Image

Body:
To open your file and convert it to byte array:

string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
// or your image directory, just replace it
var stream = File.OpenWrite(Path.Combine(directory, "image.png"));
byte[] buff = ConvertStreamToByteArray(stream);
stream.Close();

public static byte[] ConvertStreamToByteArray(Stream stream)
        {
            byte[] byteArray = new byte[16 * 1024];
            using (MemoryStream mStream = new MemoryStream())
            {
                int bit;
                while ((bit = stream.Read(byteArray, 0, byteArray.Length)) > 0)
                {
                    mStream.Write(byteArray, 0, bit);
                }
                return mStream.ToArray();
            }
        }

then, to pass this byte array to SKBitmap:

SKBitmap bmp = SKBitmap.Decode(buff);

EDIT:

If you want to try without ConvertStreamToByteArray():

byte[] buff = null;
stream.Write(buff, 0, buff.Length);

This Write will depend of the type of your stream. In this example, I'm using FileStream.

EDIT 2:

string resourceID = "image.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;

using (Stream stream = assembly.GetManifestResourceStream(resourceID))
{
   resourceBitmap = SKBitmap.Decode(stream);
   SKBitmap bmp = SKImage.FromBitmap(resourceBitmap);
}

and then you can use this bitmap to draw and fill your SKCanvas:

canvas.DrawBitmap(bmp, 0, 0);


来源: stackexchange

问:
How to do multi column sorting in angular
I want to do sorting on multiple columns, means based on first column data second column need to be sorted and based on second column data third column need to be sorted. like this I have to sort. Please suggest me how to implement this using angular component level or typescript base.</p>

答:
Try this npm plugin Its have the feature to sort multiple columns
https://www.npmjs.com/package/ngx-mat-multi-sort</p>

ContentLicense: CC BY-SA 4.0


问:
Checking out a remote branch into a new branch
Goal: git checkout -b newBranchName remotes/branchForRemote/main to actually go into newBranchName

I started with an empty Git repository, which I cloned from github.com.

Then, git remote add [urlFromAnOpenSourceProject]

Then, git checkout -b newBranchName remotes/openSourceRepo/main.

The command above only pulled the remotes/openSourceRepo/main into my own main branch. How do I instead make it pull into another of my branches (not my main branch)?

Note: I have a workaround listed below, but I would still like to know how to avoid needing to use this workaround.

My workaround: Create/switch to a different branch, and then run the following commands

```<code>brew install git-lfs (if you need git-lfs for your open source project)
git clone [My repository URL]
git remote add opensource [Open source URL]
git fetch opensource
git lfs install (if the open source project uses it.)
git checkout -b branchToPullinto
git checkout -b nameThatWillNotBeUsed remotes/opensource/main
git commit -m “I pulled from opensource into the branchToPullinto branch”
git push -> Will throw an error
git push --set-upstream origin anotherNewBranch
The Command Prompt/Terminal will say:
Branch 'anotherNewBranch' set up to track remote branch 'anotherNewBranch' from 'origin'.
Now, run “git push”
</code>```

答:
What you're doing is about right. You just forgot a git fetch --all or git fetch <open source remote name you gave it in remote add>.

So basically:

git clone https://github.com/<url to your empty repo>

git remote add opensource <link to open source project>

git fetch opensource

git checkout -b <any name you want> opensource/master

Without git fetch, your Git installation doesn't know which files/branches/tags your open source remote has in the first place.

Body:
Goal: git checkout -b newBranchName remotes/branchForRemote/main to actually go into newBranchName

I started with an empty Git repository, which I cloned from github.com.

Then, git remote add [urlFromAnOpenSourceProject]

Then, git checkout -b newBranchName remotes/openSourceRepo/main.

The command above only pulled the remotes/openSourceRepo/main into my own main branch. How do I instead make it pull into another of my branches (not my main branch)?

Note: I have a workaround listed below, but I would still like to know how to avoid needing to use this workaround.

My workaround: Create/switch to a different branch, and then run the following commands

brew install git-lfs (if you need git-lfs for your open source project)
git clone [My repository URL]
git remote add opensource [Open source URL]
git fetch opensource
git lfs install (if the open source project uses it.)
git checkout -b branchToPullinto
git checkout -b nameThatWillNotBeUsed remotes/opensource/main
git commit -m “I pulled from opensource into the branchToPullinto branch”
git push -> Will throw an error
git push --set-upstream origin anotherNewBranch
The Command Prompt/Terminal will say:
Branch 'anotherNewBranch' set up to track remote branch 'anotherNewBranch' from 'origin'.
Now, run “git push”


问:
snapshot.data[0] throwing "The Method '[ ]' cannot be unconditionally invoked because the receiver can be 'null'
Also getting

```<code>Try making the call condtional (using ?.) or adding a null check to the target
</code>```

for the same line(s):

```<code>Text("${snapshot.data[index]}")
</code>```

If I do that I get only the error message from the title.

I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:

```<code>AsyncSnapshot<Object?>
</code>```

and in the working project I see this:

```<code>AsyncSnapshot<dynamic>
</code>```

If I hover over snapshot

The entire section looks like this:

```<code>FutureBuilder(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data[index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )
</code>```

While myAsyncFunction() returns a List<dynamic> using return json.decode(response.body);

答:
In AsyncSnapshot<Object?> the object is nullable which means it can have a value or can be null. Now you are accessing the object like snapshot.data[index]. Here the snapshot.data can be null and accessing index of a null array can cause error.

So in order to access your array safely  replace snapshot.data[index] with snapshot.data?[index] ?? '' or you can use the null assertion operator like this if you are sure that your list can't be null snapshot.data![index].

Body:
Also getting

Try making the call condtional (using ?.) or adding a null check to the target

for the same line(s):

Text("${snapshot.data[index]}")

If I do that I get only the error message from the title.

I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:

AsyncSnapshot<Object?>

and in the working project I see this:

AsyncSnapshot<dynamic>

If I hover over snapshot

The entire section looks like this:

FutureBuilder(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data[index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )

While myAsyncFunction() returns a List<dynamic> using return json.decode(response.body);


问:
Groovy: MultiValueMap with Maps as keys
Heres's something I'm thinking about doing, and I want to know if you think it's a good idea or not.

I retrieve a bunch of rows from a database, which in groovy gives me a list of lists something like:

```<code>[
  [ 'Dog', 'M', 'Mutt', 'Sammy' ],
  [ 'Cat', 'F', 'Siamese', 'Pat' ],
  [ 'Dog', 'M', 'Husky', 'Taco' ],
  ...
]
</code>```

Not my real data set but you get the idea.

Since I will be pulling this data pretty frequently and doing some analysis to it before presenting it in the UI, I want to store it in a MultiValueMap keyed by groovy maps (i.e. LinkedHashMaps), so I can retrieve the bits and pieces of it that I need, without going to DB every time.  It's kind of a cache of a subset of data that comes from several tables (more complex than the animals data above).

I would be able to use it like this:

```<code>animals.get([species:'Dog', gender:'M'])
</code>```

returns:

```<code>[['Sammy', 'Mutt'], ['Taco', 'Husky'] ]
</code>```

I think I have some idea how to implement it, so I'm not really looking for that (though if you have a novel suggestion please share).  I'm mainly looking for somebody to tell me that either this won't work for some reason, or it sounds fine, or it won't scale, etc.  Or maybe there's some easier way to get a similar functionality.  One more consideration: the whole data set can sometimes be sorta large-ish, e.g. few 100k records.  If not this, what's a good way to deal with it, aside from hit the DB every time?

I realize there are lots of key/value caching solutions around, but I don't think I need anything so heavy duty for what I'm doing.  It is just a small webapp with pretty low usage, mostly internal to the company I'm building it for.

答:
If the subset of values you're using is static/deterministic, I'd just turn that into a string and use that as the key in your map.  So instead of animals.get([species:'Dog', gender:'M']), I'd use animals.get('species:Dog:gender:M').

I know you said that you were thinking that a key-value store is too heavyweight, but this is also the perfect kind of use case for Redis, which can natively store things like hash maps.

The kind of cache that you're talking about storing is exactly how we use it in production where I work, and it's been great.  It's very fast, and makes it available to all running processes without having to have a singleton, or multiple copies of very large maps.  Cache invalidation is also something you'd need to think about that redis helps to solve.

You can use the grails-redis plugin to memoize your database calls, so that it automatically checks redis first to see if it's in the cache, if it isn't, it queries the database and sticks it in the cache before returning it.  See the docs on github for more details/examples.

```<code>return redisService.memoizeHash('species:Dog:gender:M') {
    // database call that returns object, then you turn that into hash
    Dog d = Dog.findBy...
    [species: d.species, gender: d.gender, breed: d.breed, name: d.name, ...]
}
</code>```

This way, it queries the database only if Redis doesn't already have it in cache.  On cache miss, it saves the return value in redis at the specified key.

(Disclaimer, I'm the author of the grails-redis plugin, so I've got some bias)

ContentLicense: CC BY-SA 3.0

Title: Groovy: MultiValueMap with Maps as keys

Body:
Heres's something I'm thinking about doing, and I want to know if you think it's a good idea or not.

I retrieve a bunch of rows from a database, which in groovy gives me a list of lists something like:

[
  [ 'Dog', 'M', 'Mutt', 'Sammy' ],
  [ 'Cat', 'F', 'Siamese', 'Pat' ],
  [ 'Dog', 'M', 'Husky', 'Taco' ],
  ...
]

Not my real data set but you get the idea.

Since I will be pulling this data pretty frequently and doing some analysis to it before presenting it in the UI, I want to store it in a MultiValueMap keyed by groovy maps (i.e. LinkedHashMaps), so I can retrieve the bits and pieces of it that I need, without going to DB every time.  It's kind of a cache of a subset of data that comes from several tables (more complex than the animals data above).

I would be able to use it like this:

animals.get([species:'Dog', gender:'M'])

returns:

[['Sammy', 'Mutt'], ['Taco', 'Husky'] ]

I think I have some idea how to implement it, so I'm not really looking for that (though if you have a novel suggestion please share).  I'm mainly looking for somebody to tell me that either this won't work for some reason, or it sounds fine, or it won't scale, etc.  Or maybe there's some easier way to get a similar functionality.  One more consideration: the whole data set can sometimes be sorta large-ish, e.g. few 100k records.  If not this, what's a good way to deal with it, aside from hit the DB every time?

I realize there are lots of key/value caching solutions around, but I don't think I need anything so heavy duty for what I'm doing.  It is just a small webapp with pretty low usage, mostly internal to the company I'm building it for.

Body:
If the subset of values you're using is static/deterministic, I'd just turn that into a string and use that as the key in your map.  So instead of animals.get([species:'Dog', gender:'M']), I'd use animals.get('species:Dog:gender:M').

I know you said that you were thinking that a key-value store is too heavyweight, but this is also the perfect kind of use case for Redis, which can natively store things like hash maps.

The kind of cache that you're talking about storing is exactly how we use it in production where I work, and it's been great.  It's very fast, and makes it available to all running processes without having to have a singleton, or multiple copies of very large maps.  Cache invalidation is also something you'd need to think about that redis helps to solve.

You can use the grails-redis plugin to memoize your database calls, so that it automatically checks redis first to see if it's in the cache, if it isn't, it queries the database and sticks it in the cache before returning it.  See the docs on github for more details/examples.

return redisService.memoizeHash('species:Dog:gender:M') {
    // database call that returns object, then you turn that into hash
    Dog d = Dog.findBy...
    [species: d.species, gender: d.gender, breed: d.breed, name: d.name, ...]
}

This way, it queries the database only if Redis doesn't already have it in cache.  On cache miss, it saves the return value in redis at the specified key.

(Disclaimer, I'm the author of the grails-redis plugin, so I've got some bias)


问:
Xcode 10: A valid provisioning profile for this executable was not found
Since yesterday I've been getting the following error when trying run an app on my device:

A valid provisioning profile for this executable was not found."

This is after updating to Xcode 10. Building with Xcode 9 last week worked without issues. I've checked the other discussions about the error, but none of the solutions works.

The issue isn't limited to a single project I've been working on as it affects several all from different signing teams.

So far I've tried the following:

Cleaning project

Cleaning derived data

Uninstalling Xcode, deleting any preferences and files related to it.

Installing Xcode on a completely different Mac

Testing with different devices

Disabling device in developer profile and letting Xcode enable it again.

Deleting all certificates in the developer portal and recreating them

Unchecking and rechecking "Automatically manage signing"

Trashing the provisioning profile and letting Xcode recreate it

Creating a manual provisioning profile in the developer profile

The project contains no tests so there can't be a problem with wrong signing settings on that target. Date / Time is set to Automatic

One thing of note is that no Provisioning Profiles are listed here, except for the manual one I created: https://developer.apple.com/account/ios/profile/

I'd expect the xcode generated one to show up as they do for all other clients.

Below are the signing settings I'm currently using

I've yet to try downgrading Xcode to an older version to see if that works. Other than that I have no idea of what to try next.

答:
You need to manually install the development provisioning profile on the device.

In Xcode:

Go to Window > Devices and Simulators: a new window appears.

Find your connected device on the left pane. Right-click on it and select Show Provisioning Profiles...: a new window appears.

Manually add your development provisioning profile.

Re-build the app on device.


问:
Large data pairwise calculation in R
I have a super large data frame containing nearly 5 million rows.
data
then I have a char list containing around 2000 items, I need to do a pairwise(lets say one is A other is B) calculation on them, so at the end, I will have a 2000*2000 matrix containing values. The value I need is:
(#id has A and B)/ min(#id has A, #id has B)

```<code>load("data.RData")

n = length(itemlist) # n=1831

a = matrix(0, n, n)

rownames(a) <- colnames(a) <- itemlist

aa = sapply(itemlist, function(x) grepl(x, data$Item))

for(i in 1:1830) {

  for(j in (i+1):1831) {

    a1 <- aa[,i]
    a2 <- aa[,j]
    a3 <- a1 & a2

    a[i,j] <- sum(a3) / min(sum(a1), sum(a2))

  }
  print(i)
}

result <- a
</code>```

This code works but it is super slow(take days). I was wondering if it can be much faster.

答:
That's about as good as it will get building aa, but the double loop can be made much faster:

```<code>f <- function(rws) {
  aa <- matrix(sample(c(TRUE, FALSE), 1831*rws, replace = TRUE), ncol = 1831)
  n <- ncol(aa)
  cs <- colSums(aa)
  a <- matrix(0, n, n)

  for (i in 1:(n - 1L)) {
    idx <- (i + 1L):n
    a[i, idx] <- colSums(aa[aa[,i], idx, drop = FALSE])/pmin(cs[i], cs[idx])
  }

  return(a)
}

microbenchmark::microbenchmark(f(5e2), f(5e3), f(5e4), times = 1L)
#> Unit: seconds
#>      expr        min         lq       mean     median         uq        max neval
#>    f(500)   1.707038   1.707038   1.707038   1.707038   1.707038   1.707038     1
#>   f(5000)  15.397640  15.397640  15.397640  15.397640  15.397640  15.397640     1
#>  f(50000) 147.445477 147.445477 147.445477 147.445477 147.445477 147.445477     1
</code>```

This appears to be scaling pretty linearly, so I'm guessing <4 hours for 5e6 rows on a single thread with enough memory.

Title: Large data pairwise calculation in R

Body:
I have a super large data frame containing nearly 5 million rows.
data
then I have a char list containing around 2000 items, I need to do a pairwise(lets say one is A other is B) calculation on them, so at the end, I will have a 2000*2000 matrix containing values. The value I need is:
(#id has A and B)/ min(#id has A, #id has B)

load("data.RData")

n = length(itemlist) # n=1831

a = matrix(0, n, n)

rownames(a) <- colnames(a) <- itemlist

aa = sapply(itemlist, function(x) grepl(x, data$Item))

for(i in 1:1830) {

  for(j in (i+1):1831) {

    a1 <- aa[,i]
    a2 <- aa[,j]
    a3 <- a1 & a2

    a[i,j] <- sum(a3) / min(sum(a1), sum(a2))

  }
  print(i)
}

result <- a

This code works but it is super slow(take days). I was wondering if it can be much faster.

Body:
That's about as good as it will get building aa, but the double loop can be made much faster:

f <- function(rws) {
  aa <- matrix(sample(c(TRUE, FALSE), 1831*rws, replace = TRUE), ncol = 1831)
  n <- ncol(aa)
  cs <- colSums(aa)
  a <- matrix(0, n, n)

  for (i in 1:(n - 1L)) {
    idx <- (i + 1L):n
    a[i, idx] <- colSums(aa[aa[,i], idx, drop = FALSE])/pmin(cs[i], cs[idx])
  }

  return(a)
}

microbenchmark::microbenchmark(f(5e2), f(5e3), f(5e4), times = 1L)
#> Unit: seconds
#>      expr        min         lq       mean     median         uq        max neval
#>    f(500)   1.707038   1.707038   1.707038   1.707038   1.707038   1.707038     1
#>   f(5000)  15.397640  15.397640  15.397640  15.397640  15.397640  15.397640     1
#>  f(50000) 147.445477 147.445477 147.445477 147.445477 147.445477 147.445477     1

This appears to be scaling pretty linearly, so I'm guessing <4 hours for 5e6 rows on a single thread with enough memory.


问:
Save file in a specific folder
I would like to save a CSV file in a specific folder, but I can't find anywhere how to do it...
this is the code</p>
```<code># Writing on a CSV FILE
                fileToWrite = open(f"{userfinder}-{month}-{year}.csv', "a")
                fileToWrite.write('Subject,Start Date,Start Time,End Date,End Time,All Day Event,Description\n')
                fileToWrite.write(f'{string1}{tagesinfo2},{soup_datum},{soup_dienstbegin},{soup_datum},{soup_dienstende},,Kommentar: {soup_kommentar} Schiff: {b} Funktion: {soup_funktion} Schichtdauer: {soup_schichtdauer} Bezahlte Zeit: {soup_bezahltezeit} Mannschaft: {crew_list2}\n')
                fileToWrite.close()
                print(f'Datum: {soup_datum} Dienst: {string1}{tagesinfo2} --> Mannschaft: {crew_list2} --> OK')
</code>```

答:
You just have to change the working directory with os.chdir(path):

```<code>import os
path = '/Users/user/folder/example sub folder'
os.chdir(path)

#your code here
</code>```

or, as mentioned in the comments, you can use:

```<code>myfolder = "c:/foo/bar/"
fileToWrite = open(f"{myfolder}/{userfinder}-{month}-{year}.csv", "a")

#in this case the path is "{myfolder}/{userfinder}-{month}-{year}"
</code>```

This option includes the path when opening (only affects the one file) whereas os.chdir() changes the directory for everything (what I use personally for all of my projects, which are small).
If you don't want to change your folder for all files created and read, use the second option; but when you want a python file to affect every file in a distant location I would use os.chdir().

Title: Save file in a specific folder

Body:
I would like to save a CSV file in a specific folder, but I can't find anywhere how to do it...
this is the code

# Writing on a CSV FILE
                fileToWrite = open(f"{userfinder}-{month}-{year}.csv', "a")
                fileToWrite.write('Subject,Start Date,Start Time,End Date,End Time,All Day Event,Description\n')
                fileToWrite.write(f'{string1}{tagesinfo2},{soup_datum},{soup_dienstbegin},{soup_datum},{soup_dienstende},,Kommentar: {soup_kommentar} Schiff: {b} Funktion: {soup_funktion} Schichtdauer: {soup_schichtdauer} Bezahlte Zeit: {soup_bezahltezeit} Mannschaft: {crew_list2}\n')
                fileToWrite.close()
                print(f'Datum: {soup_datum} Dienst: {string1}{tagesinfo2} --> Mannschaft: {crew_list2} --> OK')

Body:
You just have to change the working directory with os.chdir(path):

import os
path = '/Users/user/folder/example sub folder'
os.chdir(path)

#your code here

or, as mentioned in the comments, you can use:

myfolder = "c:/foo/bar/"
fileToWrite = open(f"{myfolder}/{userfinder}-{month}-{year}.csv", "a")

#in this case the path is "{myfolder}/{userfinder}-{month}-{year}"

This option includes the path when opening (only affects the one file) whereas os.chdir() changes the directory for everything (what I use personally for all of my projects, which are small).
If you don't want to change your folder for all files created and read, use the second option; but when you want a python file to affect every file in a distant location I would use os.chdir().


问:
How to identify unique values from a csv with row breaks in R
I have a csv with a line break that I import to R using the read.csv feature and I want to identify the unique values in one of the columns.  For example my example.csv file looks like this:

I believe I can use unique after I delete the empty row which I do like this:

```<code>df <- read.csv(file = "example.csv",header = FALSE)

colnames(df)[1:2] <- c("path","group")
df <- df[!(df$path=="" | df$group==""), ]

unique_groups <- unique(df$group)
</code>```

However, unique_groups (despite only having 3 different groups), turns out to be a factor with 4 levels, my 3 different groups and then blank or "".

I have figured out that if I save df as a csv right before the unique_groups step and the read back in that csv, it works fine and then unique_groups is a factor with 3 levels, but I'm wondering if there is a more efficient way to do this?  Am I doing something wrong with the initial import or how I remove the blank row?

Any help is appreciated - thanks!

答:
Turns out when I imported my csv, it was classifying column B as a factor which was causing my problems.  So now I just import it as a character class and that has resolved my issue, like so:</p>
```<code>df <- read.csv(file = "example.csv",header = FALSE, colClasses = c("character","character"))
</code>```

Body:
I have a csv with a line break that I import to R using the read.csv feature and I want to identify the unique values in one of the columns.  For example my example.csv file looks like this:

I believe I can use unique after I delete the empty row which I do like this:

df <- read.csv(file = "example.csv",header = FALSE)

colnames(df)[1:2] <- c("path","group")
df <- df[!(df$path=="" | df$group==""), ]

unique_groups <- unique(df$group)

However, unique_groups (despite only having 3 different groups), turns out to be a factor with 4 levels, my 3 different groups and then blank or "".

I have figured out that if I save df as a csv right before the unique_groups step and the read back in that csv, it works fine and then unique_groups is a factor with 3 levels, but I'm wondering if there is a more efficient way to do this?  Am I doing something wrong with the initial import or how I remove the blank row?

Any help is appreciated - thanks!

Body:
Turns out when I imported my csv, it was classifying column B as a factor which was causing my problems.  So now I just import it as a character class and that has resolved my issue, like so:

df <- read.csv(file = "example.csv",header = FALSE, colClasses = c("character","character"))


问:
pass command-line arguments to runpy
I have two files, one which has a side effect I care about that occurs within the if __name__ == "__main__" guard:

# a.py
d = {}
if __name__ == "__main__":
    d['arg'] = 'hello'
```

<p>The second file imports the first (using <code>runpy</code>) and prints the dictionary:</p>

<pre class="lang-py prettyprint-override"><code># b.py
import runpy
m = runpy.run_module('a', run_name='__main__')
print(m['d'])  # {'arg': 'hello'}
</code>```

So far this works.  But now I want to change the first file to accept a command line argument:

import sys
d = {}
if __name__ == "__main__":
    d['arg'] = process(sys.argv[1])
```

The problem is that process() is written by someone else and outside of my control, but I still want to get the updated dictionary d after it has been "processed".

How can I mock sys.argv before calling runpy, or otherwise provide that value to a.py?

答:
For those who stumbled across this post like me, you can just pass the command line arguments directly. As an example, if I have

# a.py
import argparse

def parse_args():
    # fmt: off
    parser = argparse.ArgumentParser()
    parser.add_argument("--myvar")
    args = parser.parse_args()
    # fmt: on
    return args

if __name__ == "__main__":
    args = parse_args()
    print(args.myvar)
```
<pre class="lang-py prettyprint-override"><code># b.py

import runpy
runpy.run_path(path_name='a.py', run_name="__main__")
</code>```

I get

$ python a.py
None
$ python a.py --myvar test
test
$ python b.py
None
$ python b.py --myvar test
test
```

Title: pass command-line arguments to runpy

Body:
I have two files, one which has a side effect I care about that occurs within the if __name__ == "__main__" guard:

# a.py
d = {}
if __name__ == "__main__":
    d['arg'] = 'hello'

The second file imports the first (using runpy) and prints the dictionary:

# b.py
import runpy
m = runpy.run_module('a', run_name='__main__')
print(m['d'])  # {'arg': 'hello'}

So far this works.  But now I want to change the first file to accept a command line argument:

import sys
d = {}
if __name__ == "__main__":
    d['arg'] = process(sys.argv[1])

The problem is that process() is written by someone else and outside of my control, but I still want to get the updated dictionary d after it has been "processed".

How can I mock sys.argv before calling runpy, or otherwise provide that value to a.py?

Body:
For those who stumbled across this post like me, you can just pass the command line arguments directly. As an example, if I have

# a.py
import argparse

def parse_args():
    # fmt: off
    parser = argparse.ArgumentParser()
    parser.add_argument("--myvar")
    args = parser.parse_args()
    # fmt: on
    return args

if __name__ == "__main__":
    args = parse_args()
    print(args.myvar)

# b.py

import runpy
runpy.run_path(path_name='a.py', run_name="__main__")

I get

$ python a.py
None
$ python a.py --myvar test
test
$ python b.py
None
$ python b.py --myvar test
test


问:
Android Outofmemory error, external memory
I created an emulator with Android 2.2 kernel and max VM heap size =24Mb. When an activity runs on it, the logcat show outofmemory error:

```<code>"861984-byte external allocation too larger for this process"
</code>```

Can I know what does "external allocation" here mean? Is this the "external memory"? This activity call setContentView(R.layout.main).

The layout main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/login_bg"
>
<ImageView
android:layout_width="190dp"
android:layout_height="50dp"
android:scaleType = "fitXY"
android:layout_gravity="center"
android:src="@drawable/login_btn_fb"
android:id="@+id/facebookconnect"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility = "visible"
android:src="@drawable/splash"
android:scaleType = "fitXY"
android:id="@+id/splashscreen"
/>
</FrameLayout>
</code>```

The dimension of image splash.png is 640*960

Before Honeycomb, pixel data of image was stored in "native memory". Is "native memory" the same as "external memory"?

答: set your imageview to null each time when you load the new image.Or use recycle() method to your imageview object each time when you load the new image</p>

Body:
I created an emulator with Android 2.2 kernel and max VM heap size =24Mb. When an activity runs on it, the logcat show outofmemory error:

"861984-byte external allocation too larger for this process"

Can I know what does "external allocation" here mean? Is this the "external memory"? This activity call setContentView(R.layout.main).

The layout main.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/login_bg"
>
<ImageView
android:layout_width="190dp"
android:layout_height="50dp"
android:scaleType = "fitXY"
android:layout_gravity="center"
android:src="@drawable/login_btn_fb"
android:id="@+id/facebookconnect"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility = "visible"
android:src="@drawable/splash"
android:scaleType = "fitXY"
android:id="@+id/splashscreen"
/>
</FrameLayout>

The dimension of image splash.png is 640*960

Before Honeycomb, pixel data of image was stored in "native memory". Is "native memory" the same as "external memory"?


问:
DELETE method requires query parameter instead of path parameter in next.js
I am creating a CRUD in API,
but the delete does not seems to work properly.
I get a response from this

```<code>http://localhost:3000/api/admin/categories?id=1
</code>```

and not from this

```<code>http://localhost:3000/api/admin/categories/1
</code>```

this is the code in next.js:

```<code>export default async (req, res) => {
  const {
    query: { id },
    method,
  } = req;

  switch (method) {
    case "DELETE":
      return res.status(200).json({
        success: true,
        id: id,
      });
    }
</code>```

in React:

```<code> axios.delete(`http://localhost:3000/api/admin/categories/`, {id: 1})
</code>```

The same situation is also with "PUT" method

Folder Directory:

```<code>api
|
---admin
--------categories
--------index.js
</code>```

答:
If you want to create API Routes such as DELETE, PUT ( they require /id as path parameter), you should create a separate file in that folder.

Like this:

```<code>api
|
---admin
--------categories
--------index.js
--------[id].js
</code>```

And in the [id].js file:

```<code>export default function handler(req, res) {
  const { id } = req.query;
  if (req.method === "DELETE") {
    res.end(`Category: ${id}`);
  }
}
</code>```

Body:
I am creating a CRUD in API,
but the delete does not seems to work properly.
I get a response from this

http://localhost:3000/api/admin/categories?id=1

and not from this

http://localhost:3000/api/admin/categories/1

this is the code in next.js:

export default async (req, res) => {
  const {
    query: { id },
    method,
  } = req;

  switch (method) {
    case "DELETE":
      return res.status(200).json({
        success: true,
        id: id,
      });
    }

in React:

 axios.delete(`http://localhost:3000/api/admin/categories/`, {id: 1})

The same situation is also with "PUT" method

Folder Directory:

api
|
---admin
--------categories
--------index.js

Body:
If you want to create API Routes such as DELETE, PUT ( they require /id as path parameter), you should create a separate file in that folder.

Like this:

api
|
---admin
--------categories
--------index.js
--------[id].js

And in the [id].js file:

export default function handler(req, res) {
  const { id } = req.query;
  if (req.method === "DELETE") {
    res.end(`Category: ${id}`);
  }
}


问:
visual studio is not supporting python
My visual studio and python was working fine everything was going smoothly I just download a XAMPP  after downloading it my vs studio is not recognizing python I delete this software and vs studio and python, download it again but it is again giving the same error can be seen from figure attach. 1</p>

答: Did you installed python extention? Go to "Extentons" on the left side of screen, enter Python and install the first extention. If need - restart vscode. Should work</p>

Title: visual studio is not supporting python


问:
How to move table row to the top within a loop - React
I have a loop which goes through an array (files) of objects (person). If the person works as a doctor or a vet I would like to display their row at the top of the table, if not, they should be displayed under the doctors and vets. I have a sample piece of code as to where i believe the code should be (See: <PLACE AT TOP OF TABLE>). I've been over and back with solutions and can't get anything solid. I have tried to add these persons to an array, add them to a new table component and insert the table here but no avail. Any tips would be greatly appreciated.

```<code><tbody>
{props.files.map(person=> (
    <div>
        {(person.job === "doctor" || person.job === "vet") ? <PLACE AT TOP OF TABLE> :
            <tr>
                <td>{person.name}</td>
                <td>{person.age}</td>
                <td>{person.job}</td>
            </tr>
         }
    </div>
))}
</tbody>
</code>```

答: You can use two different loops, the first loop, which searches for a doctor or a vet, occurs at the top of a table, then the second loop shows the others except the doctors and the vets</p>

Body:
I have a loop which goes through an array (files) of objects (person). If the person works as a doctor or a vet I would like to display their row at the top of the table, if not, they should be displayed under the doctors and vets. I have a sample piece of code as to where i believe the code should be (See: <PLACE AT TOP OF TABLE>). I've been over and back with solutions and can't get anything solid. I have tried to add these persons to an array, add them to a new table component and insert the table here but no avail. Any tips would be greatly appreciated.

{props.files.map(person=> (

        {(person.job === "doctor" || person.job === "vet") ? <PLACE AT TOP OF TABLE> :

                {person.name}
                {person.age}
                {person.job}

         }

))}


问:
phpmyadmin security
I have a production server with apache2, php, mysql.
I have just one site right now (mysite.com) as a virtual host.  I want to put phpmyadmin, webalizer, and maybe webmin on there.  So far, I installed phpmyadmin, and it works but the whole internet can go to mysite.com/phpmyadmin

How can I reduce the visibility to say 192.168.0.0/16 so it's just accessible to machines behind my firewall?

答:
1) You can do it at the Webserver level.

Use allow/deny rules for apache. If you don't have direct access to your apache configuration file, you may use a .htaccess file.

```<code><Directory /docroot>
    Order Deny,Allow
    Deny from all
    Allow from 10.1.2.3
</Directory>
</code>```

2) You can do it at the application level using the phpmyadmin config file.

The configuration parameter is: $cfg['Servers'][$i]['AllowDeny']['rules']

Examples of rules are:

```<code>'all' -> 0.0.0.0/0
'localhost' -> 127.0.0.1/8
'localnetA' -> SERVER_ADDRESS/8
'localnetB' -> SERVER_ADDRESS/16
'localnetC' -> SERVER_ADDRESS/24
</code>```

You can see this on the official phpMyAdmin configuration documentation.

http://www.phpmyadmin.net/documentation/#servers_allowdeny_order

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

Title: phpmyadmin security

Body:
1) You can do it at the Webserver level.

Use allow/deny rules for apache. If you don't have direct access to your apache configuration file, you may use a .htaccess file.

<Directory /docroot>
    Order Deny,Allow
    Deny from all
    Allow from 10.1.2.3
</Directory>

2) You can do it at the application level using the phpmyadmin config file.

The configuration parameter is: $cfg['Servers'][$i]['AllowDeny']['rules']

Examples of rules are:

'all' -> 0.0.0.0/0
'localhost' -> 127.0.0.1/8
'localnetA' -> SERVER_ADDRESS/8
'localnetB' -> SERVER_ADDRESS/16
'localnetC' -> SERVER_ADDRESS/24

You can see this on the official phpMyAdmin configuration documentation.

http://www.phpmyadmin.net/documentation/#servers_allowdeny_order

OwnerDisplayName: Wadih M.

LastEditorDisplayName: Wadih M.


问:
How to drop the Rows in a sql table for a particular string value
The sql query SELECT * FROM StudentRecord WHERE courseName like "SCIENCE"; gives me all the rows in the studentRecord table's column has "SCIENCE".

What is the query if I want to fetch all the rows in the table except where "SCIENCE" is there?

答:
```<code>SELECT * FROM StudentRecord
WHERE courseName NOT LIKE "SCIENCE%";
</code>```

you can try this way

ıf you want more info check this doc

https://www.postgresqltutorial.com/postgresql-like/

Body:
SELECT * FROM StudentRecord
WHERE courseName NOT LIKE "SCIENCE%";

you can try this way

ıf you want more info check this doc

https://www.postgresqltutorial.com/postgresql-like/


问:
Predefined type 'System.Void' is not defined or imported during Visual Studio Online build of ASP.NET 5
I get this error when I try to build the project in Visual Studio Online:

```<code>…\Frontend\Startup.cs(65,49): Error CS0518: Predefined type 'System.Void' is not defined or imported
…\Frontend\Startup.cs(65,49): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Void' is not defined or imported [C:\a\1\s\Frontend\src\Frontend\Frontend.xproj]
</code>```

It seems that the error happens in the place where I reference another library (package class library).

P.S. I had some conversation about this here: Easy way to build and deploy (to Azure) ASP.NET 5 in Visual Studio Team Services, but there was no answer after all, so I still cannot build it...

Web project.json:

```<code>"dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Web.Common": "1.0.0-*"
},

"frameworks": {
    "dnx451": { },
    "dnxcore50": { }
},
</code>```

Library project.json

```<code>"frameworks": {
    "dnx451": { },
    "dnxcore50": {
        "dependencies": {
            "Microsoft.CSharp": "4.0.1-beta-23516",
            "System.Collections": "4.0.11-beta-23516",
            "System.Linq": "4.0.1-beta-23516",
            "System.Runtime": "4.0.21-beta-23516",
            "System.Threading": "4.0.11-beta-23516"
      }
    }
  },
"dependencies": {
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final"
  }
</code>```

Update (problem and solution):

The problem was in the fact that my library reference was not in the same folder and the script by default does not run dnu-restore there, so I had to go one level up and start finding project.json recursively there

```<code>$SourceRoot = Split-Path -Path $PSScriptRoot -Parent

# run DNU restore on all project.json files in the src folder including 2>1 to redirect stderr to stdout for badly behaved tools
Get-ChildItem -Path $SourceRoot -Filter project.json -Recurse | ForEach-Object { & dnu restore $_.FullName 2>1 }
</code>```

Thanks Eddie - MSFT for help!

答:
Restart visual studio it will resolve the problem.
It  was the case for me.</p>

Body:
I get this error when I try to build the project in Visual Studio Online:

…\Frontend\Startup.cs(65,49): Error CS0518: Predefined type 'System.Void' is not defined or imported
…\Frontend\Startup.cs(65,49): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Void' is not defined or imported [C:\a\1\s\Frontend\src\Frontend\Frontend.xproj]

It seems that the error happens in the place where I reference another library (package class library).

P.S. I had some conversation about this here: Easy way to build and deploy (to Azure) ASP.NET 5 in Visual Studio Team Services, but there was no answer after all, so I still cannot build it...

Web project.json:

"dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Web.Common": "1.0.0-*"
},

"frameworks": {
    "dnx451": { },
    "dnxcore50": { }
},

Library project.json

"frameworks": {
    "dnx451": { },
    "dnxcore50": {
        "dependencies": {
            "Microsoft.CSharp": "4.0.1-beta-23516",
            "System.Collections": "4.0.11-beta-23516",
            "System.Linq": "4.0.1-beta-23516",
            "System.Runtime": "4.0.21-beta-23516",
            "System.Threading": "4.0.11-beta-23516"
      }
    }
  },
"dependencies": {
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final"
  }

Update (problem and solution):

The problem was in the fact that my library reference was not in the same folder and the script by default does not run dnu-restore there, so I had to go one level up and start finding project.json recursively there

$SourceRoot = Split-Path -Path $PSScriptRoot -Parent

# run DNU restore on all project.json files in the src folder including 2>1 to redirect stderr to stdout for badly behaved tools
Get-ChildItem -Path $SourceRoot -Filter project.json -Recurse | ForEach-Object { & dnu restore $_.FullName 2>1 }

Thanks Eddie - MSFT for help!


问:
Simple Markdown subset features in PHP
I would like to allow only paragraphs and lists.

Actually i want to use the input to create a document in Open Document format. So I replace the tag
 with the correct tag in ODF. But first, I'm trying to learn how to transform the markdown format into something I can use.

I could use the output of MarkdownPHP and replace tags in html to ODF tags, however i want to use only the paragraphs and lists. The Markdown generates much more than i need. If i miss any html tag the ODF document will break because it don't understand html tags.

I believe it is possible to use a simple RegExp. But I don't know how!

example:

```<code>My first line.

*    My first item.
*    My second item.

More text...
</code>```

output:

My first line.

My first item.

My second item.

More text...

```

答:
You can use the strip_tags() function to remove all tags other than the ones you want. Their contents will remain, but the tags themselves will be removed.

Try this:

```<code>$output = strip_tags($output, "<p><ul><ol><li>");
</code>```

From there, you can just use str_replace() to change the remaining tags into their ODF counterparts. (If the tag format isn't consistent coming out of your Markdown parser, then you can just use preg_replace() to handle the differences depending on the specific output).

Title: Simple Markdown subset features in PHP

Body:
I would like to allow only paragraphs and lists.

Actually i want to use the input to create a document in Open Document format. So I replace the tag
 with the correct tag in ODF. But first, I'm trying to learn how to transform the markdown format into something I can use.

I could use the output of MarkdownPHP and replace tags in html to ODF tags, however i want to use only the paragraphs and lists. The Markdown generates much more than i need. If i miss any html tag the ODF document will break because it don't understand html tags.

I believe it is possible to use a simple RegExp. But I don't know how!

example:

My first line.

*    My first item.
*    My second item.

More text...

output:

My first line.

My first item.

My second item.

More text...

Body:
You can use the strip_tags() function to remove all tags other than the ones you want. Their contents will remain, but the tags themselves will be removed.

Try this:

$output = strip_tags($output, "<p><ul><ol><li>");

From there, you can just use str_replace() to change the remaining tags into their ODF counterparts. (If the tag format isn't consistent coming out of your Markdown parser, then you can just use preg_replace() to handle the differences depending on the specific output).


问:
How can I swap internal IP address between two GCP VMs?
I have a running VM1 (internal IP is: xxx.xxx.0.7). I will create another new VM2 and I want to change the IP of VM1 to any other IP and set the IP of VM2 to "xxx.xxx.0.7". OS of both VM is windows server.

I have found some way to change the IP of a running VM. But I am not sure if that works. Is there any straightforward way to do this?

Thanks in advance!

答:
First - for this operation you will need to stop your VM1. But I believe this is not a concern since you are planning to make VM2 work as VM1.

Second - It's impossible to attach new or existing static internal IP to an existing VM.

If you want to reserve internal IP address for VM2 then the only way I know is the first method I described.

First method - switch disks. Simple but may require some configuration after the switch.

create VM2 (may be identical but you may add processors or RAM if you need)

configure VM2 with all you need to do the job of VM1

clone VM2's boot disk (lets call it disk22)

stop VM1

detach a boot disk from VM1

attach disk22 to VM2 (just like you would switch disks on a regular PC)

start VM1 (but running off of a VM2's cloned disk)

Done. Very simple and elegant. You can then Create another VM using VM1's old disk (which is detached at the moment).

I don't know if there will be any issues with booting Windows or any other running services (that may have depend on the old VM'2 IP) but this is your part.

Second method - switch addresses. More complicated but you may loose your original IP - but if you're the only person having administration rights to this VPC (or a project) then you should be OK.

Ephemeral internal IP addresses: these addresses are available to VM instances and forwarding rules. Ephemeral internal IP addresses remain attached to VM instances and forwarding rules until the instance or forwarding rule is deleted.

Procedure is as fallows (for this example my VPC network name was default - if yours is names otherwise please make proper changes).

create new VM2 with all needed configuration

stop VM2

create new VPC and call it lan1 (or whatever you like)

change Network on VM2's primary network interface to lan1 (select ephemeral internal IP address):

stop VM1

note VM1's IP - lets call it ip1

change Network on VM1's primary network interface to lan1 and select "Ephemeral (automatic) as Primary Internal IP:

change Network on VM2's primary network interface to default and select as "Ephemeral (custom)" Primary Internal IP and type the noted earlied IP in the "address" field.

start VM2

Why going through lan1 ? For some reason GCP console refuses to change even ephemeral (custom) address to different one:

This way you end up with VM2 having address you wanted.

If you want it to be a static one you need to promote it.

Both methods minimise the downtime to a couple of minutes.

If you're OK with a longer downtime and can create&configure you new VM quick then you can turn off VM1, change it's IP, reserve it as a new static internal IP and then create VM2 with that IP.


问:
Retain duplicates in the given list using Stream API
I want to find the duplicates in a set of identifier objects.

Example:

NE , SN1

NE , SN

NE1 , SN

NE , SN1

The result should be NE, SN1 in the List.

```<code>class Identifier {

 String reference;//NE

 String number;//SN1

 String digiId; //Not used for duplicate identification

//getters and setters
}

public static List<Identifier> getDuplicates(List<Identifier> list) {
        Map<String, Map<String, Long>> noOfDupliactes = list.stream().
            collect(Collectors.groupingBy(Identifier::getReference,Collectors.groupingBy(Identifier::getNumber, Collectors.counting())));

**//How to process noOfDupliactes in Java8 using stream to get the List<Identifier>?**

}
</code>```

Any help would be appreciated.

答:
I assume that equals/hashCode of the Identifier doesn't match your requirements and cant be changed.

From your example, I understood that you want to get one representative for each duplicate combination of number and reference.

The first approach utilizes streams. Firstly it creates a map, filters out buckets with a single value, peeks one element from every bucket with duplicates, and collects to List.

```<code>    public static List<Identifier> getDuplicates(List<Identifier> list) {
        return list.stream()
                .collect(Collectors.groupingBy(IdWrapper::new))
                .values().stream()
                .filter(identifiers -> identifiers.size() > 1)
                .map(identifiers -> identifiers.stream().findAny().orElseThrow())
                .toList();
    }
</code>```

For this solution record IdWrapper can be implemented like this:

```<code>    record IdWrapper(String reference, String number) {
        IdWrapper(final Identifier identifier) {
            this(identifier.reference, identifier.number);
        }
    }
</code>```

The second approach requires a single traversal over the given list.

Every element of the list is checked against the set, if an element gets rejected by the set that means it's duplicate.

```<code>    public static List<Identifier> getDuplicates(List<Identifier> list) {
        Set<IdWrapper> wrappers = new HashSet<>();
        Set<IdWrapper> duplicates = new HashSet<>();
        for (Identifier id: list) {
            IdWrapper wrapper = new IdWrapper(id);
            if (!wrappers.add(wrapper)) {
                duplicates.add(wrapper);
            }
        }
        return unwrap(duplicates);
    }
</code>```
```<code>    private static List<Identifier> unwrap(Collection<IdWrapper> duplicates) {
        return duplicates.stream()
                .map(IdWrapper::getId)
                .toList(); // for Java 16 and above == collect(Collectors.toList())
    }
</code>```

Record IdWrapper (could be implemented as a class if you are using Java 15 or earlier) is used to establish uniqueness (i.e. provide equals and hashCode) based on the number and reference of the Identifier object.

```<code>    record IdWrapper(Identifier id) {

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            IdWrapper other = (IdWrapper) o;
            return this.id.reference.equals(other.id.reference) && this.id.number.equals(other.id.number);
        }

        @Override
        public int hashCode() {
            return Objects.hash(this.id.reference, this.id.number);
        }
    }
</code>```
```<code>    public static void main(String[] args) {
        List<Identifier> ids = List.of(
                new Identifier("NE" , "SN1"),
                new Identifier("NE" , "SN"),
                new Identifier("NE1" , "SN"),
                new Identifier("NE" , "SN1")
        );

        System.out.println(getDuplicates(ids));
    }
</code>```

output (identical for both versions of getDuplicates())

```<code>    [Identifier{reference='NE', number='SN1'}]
</code>```

Body:
I want to find the duplicates in a set of identifier objects.

Example:

NE , SN1

NE , SN

NE1 , SN

NE , SN1

The result should be NE, SN1 in the List.

class Identifier {

 String reference;//NE

 String number;//SN1

 String digiId; //Not used for duplicate identification

//getters and setters
}

public static List<Identifier> getDuplicates(List<Identifier> list) {
        Map<String, Map<String, Long>> noOfDupliactes = list.stream().
            collect(Collectors.groupingBy(Identifier::getReference,Collectors.groupingBy(Identifier::getNumber, Collectors.counting())));

**//How to process noOfDupliactes in Java8 using stream to get the List<Identifier>?**

}

Any help would be appreciated.

Body:
I assume that equals/hashCode of the Identifier doesn't match your requirements and cant be changed.

From your example, I understood that you want to get one representative for each duplicate combination of number and reference.

The first approach utilizes streams. Firstly it creates a map, filters out buckets with a single value, peeks one element from every bucket with duplicates, and collects to List.

    public static List<Identifier> getDuplicates(List<Identifier> list) {
        return list.stream()
                .collect(Collectors.groupingBy(IdWrapper::new))
                .values().stream()
                .filter(identifiers -> identifiers.size() > 1)
                .map(identifiers -> identifiers.stream().findAny().orElseThrow())
                .toList();
    }

For this solution record IdWrapper can be implemented like this:

    record IdWrapper(String reference, String number) {
        IdWrapper(final Identifier identifier) {
            this(identifier.reference, identifier.number);
        }
    }

The second approach requires a single traversal over the given list.

Every element of the list is checked against the set, if an element gets rejected by the set that means it's duplicate.

    public static List<Identifier> getDuplicates(List<Identifier> list) {
        Set<IdWrapper> wrappers = new HashSet<>();
        Set<IdWrapper> duplicates = new HashSet<>();
        for (Identifier id: list) {
            IdWrapper wrapper = new IdWrapper(id);
            if (!wrappers.add(wrapper)) {
                duplicates.add(wrapper);
            }
        }
        return unwrap(duplicates);
    }

    private static List<Identifier> unwrap(Collection<IdWrapper> duplicates) {
        return duplicates.stream()
                .map(IdWrapper::getId)
                .toList(); // for Java 16 and above == collect(Collectors.toList())
    }

Record IdWrapper (could be implemented as a class if you are using Java 15 or earlier) is used to establish uniqueness (i.e. provide equals and hashCode) based on the number and reference of the Identifier object.

    record IdWrapper(Identifier id) {

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            IdWrapper other = (IdWrapper) o;
            return this.id.reference.equals(other.id.reference) && this.id.number.equals(other.id.number);
        }

        @Override
        public int hashCode() {
            return Objects.hash(this.id.reference, this.id.number);
        }
    }

    public static void main(String[] args) {
        List<Identifier> ids = List.of(
                new Identifier("NE" , "SN1"),
                new Identifier("NE" , "SN"),
                new Identifier("NE1" , "SN"),
                new Identifier("NE" , "SN1")
        );

        System.out.println(getDuplicates(ids));
    }

output (identical for both versions of getDuplicates())

    [Identifier{reference='NE', number='SN1'}]


问:
How to move data to next column in Scala
I'm having a problem trying to update my table. I receive a new date and a new state, but I also want to update the history of dates and states, removing the last case(date2, state2) if it would be filled. I need some kind of loop or function to do it properly for not hard coding every single column.

My main though failed because I misunderstand the concept. I was trying to create a ordered list of dates for locating in the right column but I got stucked when I realise about the state.

I have run out of ideas but still didn't reach a significant code. I just cannot get to any basic code. I would appreciate any help.

Input

```<code>val historic = Seq(("Alice", "2022-01-02", "2", "2021-04-06", "3", "2020-01-01", "1")).toDF("name", "currentDate", "currentState", "date1", "state1", "date2", "state2").show()
+-----+-----------+------------+----------+------+----------+------+
| name|currentDate|currentState|     date1|state1|     date2|state2|
+-----+-----------+------------+----------+------+----------+------+
|Alice| 2022-01-02|           2|2021-04-06|     3|2020-01-01|     1|
+-----+-----------+------------+----------+------+----------+------+

val newData = Seq(("Alice", "2022-02-02", "s1")).toDF("name", "date", "state").show()
+-----+----------+-----+
| name|      date|state|
+-----+----------+-----+
|Alice|2022-02-02|   s1|
+-----+----------+-----+
</code>```

Desired output

```<code>val expected = Seq(("Alice", "2022-02-02", "s1", "2022-01-02", "2", "2021-04-06", "3")).toDF("name", "currentDate", "currentState", "date1", "state1", "date2", "state2").show()
+-----+-----------+------------+----------+------+----------+------+
| name|currentDate|currentState|     date1|state1|     date2|state2|
+-----+-----------+------------+----------+------+----------+------+
|Alice| 2022-02-02|          s1|2022-01-02|     2|2021-04-06|     3|
+-----+-----------+------------+----------+------+----------+------+
</code>```

Thanks

答:
This should do what you need:

```<code>val expected = historic.join(newData, Seq("name")).select(
  'name,
  'currentDate as "oldDate",
  'currentState as "oldState",
  'date as "newDate",
  'state,
  'state1 as "oldS1",
  'date1 as "oldD1",
).select(
  'name,
  'newDate as "currentDate",
  'state as "currentState",
  'oldState as "state1",
  'oldDate as "date1",
  'oldS1 as "state2",
  'oldD1 as "date2"
)
</code>```

It adds the new data to the old based on the name column (making the assumption that that is unique), and then renames the columns to give you the desired structure.

Body:
I'm having a problem trying to update my table. I receive a new date and a new state, but I also want to update the history of dates and states, removing the last case(date2, state2) if it would be filled. I need some kind of loop or function to do it properly for not hard coding every single column.

My main though failed because I misunderstand the concept. I was trying to create a ordered list of dates for locating in the right column but I got stucked when I realise about the state.

I have run out of ideas but still didn't reach a significant code. I just cannot get to any basic code. I would appreciate any help.

Input

val historic = Seq(("Alice", "2022-01-02", "2", "2021-04-06", "3", "2020-01-01", "1")).toDF("name", "currentDate", "currentState", "date1", "state1", "date2", "state2").show()
+-----+-----------+------------+----------+------+----------+------+
| name|currentDate|currentState|     date1|state1|     date2|state2|
+-----+-----------+------------+----------+------+----------+------+
|Alice| 2022-01-02|           2|2021-04-06|     3|2020-01-01|     1|
+-----+-----------+------------+----------+------+----------+------+

val newData = Seq(("Alice", "2022-02-02", "s1")).toDF("name", "date", "state").show()
+-----+----------+-----+
| name|      date|state|
+-----+----------+-----+
|Alice|2022-02-02|   s1|
+-----+----------+-----+

Desired output

val expected = Seq(("Alice", "2022-02-02", "s1", "2022-01-02", "2", "2021-04-06", "3")).toDF("name", "currentDate", "currentState", "date1", "state1", "date2", "state2").show()
+-----+-----------+------------+----------+------+----------+------+
| name|currentDate|currentState|     date1|state1|     date2|state2|
+-----+-----------+------------+----------+------+----------+------+
|Alice| 2022-02-02|          s1|2022-01-02|     2|2021-04-06|     3|
+-----+-----------+------------+----------+------+----------+------+

Thanks

Body:
This should do what you need:

val expected = historic.join(newData, Seq("name")).select(
  'name,
  'currentDate as "oldDate",
  'currentState as "oldState",
  'date as "newDate",
  'state,
  'state1 as "oldS1",
  'date1 as "oldD1",
).select(
  'name,
  'newDate as "currentDate",
  'state as "currentState",
  'oldState as "state1",
  'oldDate as "date1",
  'oldS1 as "state2",
  'oldD1 as "date2"
)

It adds the new data to the old based on the name column (making the assumption that that is unique), and then renames the columns to give you the desired structure.


问:
Unable to find package <local.Package>. No packages exist with this id in source(s): nuget.org
We have developed an API using .Net Core 5. We now wish to deploy that API as a Azure Web App. We use GitHub so opted to integrate deployment of this API with GitHub Actions.

This process seems straight forward enough, however, one of the nuget packages we use has been provided to us via sftp from a third party (we only have the .nupkg files locally on our machines).

If we trigger the build we simply get a lot of errors resembling this:

```<code>error NU1101: Unable to find package <ThirdParty.Package.Name>. No packages exist with this id in source(s): nuget.org
</code>```

As the error states it is unable to find the package at "nuget.org", because it does not exist there.

Somehow we need to make these packages available to GitHub Actions build process. I have looked into GitHub Packages, but do not see how we could get the third party nuget packages into GitHub Packages because we do not have access to the source code, only the .nupkg files.

答:
To anyone running into this, I managed to resolve this by doing the following:

In my personal GitHub account, I generated a Personal Access Token (PAT) with package write permissions.

I installed gpr onto my machine:
dotnet tool install gpr -g

Pushed the package to GitHub:

```<code>gpr push ".\path-to-package\Packge.Name.1.1.1.nupkg" -r https://github.com/UsernameOrOrganization/repo-name -k <Your PAT>
</code>```

Body:
We have developed an API using .Net Core 5. We now wish to deploy that API as a Azure Web App. We use GitHub so opted to integrate deployment of this API with GitHub Actions.

This process seems straight forward enough, however, one of the nuget packages we use has been provided to us via sftp from a third party (we only have the .nupkg files locally on our machines).

If we trigger the build we simply get a lot of errors resembling this:

error NU1101: Unable to find package <ThirdParty.Package.Name>. No packages exist with this id in source(s): nuget.org

As the error states it is unable to find the package at "nuget.org", because it does not exist there.

Somehow we need to make these packages available to GitHub Actions build process. I have looked into GitHub Packages, but do not see how we could get the third party nuget packages into GitHub Packages because we do not have access to the source code, only the .nupkg files.

Body:
To anyone running into this, I managed to resolve this by doing the following:

In my personal GitHub account, I generated a Personal Access Token (PAT) with package write permissions.

I installed gpr onto my machine:
dotnet tool install gpr -g

Pushed the package to GitHub:

gpr push ".\path-to-package\Packge.Name.1.1.1.nupkg" -r https://github.com/UsernameOrOrganization/repo-name -k <Your PAT>


问:
pytest-cov cover many applications at once
I built django project with many applications. Now I want to generate a coverage report for these applications.  For testing purposes, I use py.test, pytest-django and pytest-cov.  So far, I can generate the report only by typing all my app names manually on the command line:

```<code>py.test --cov-report html --cov=app1 --cov=app2 --cov=app3 --cov=app4 */tests.py
</code>```

Does pytest-cov have a way to specify all the applications with a simple expression?

答:
Before

After

Change this line in pytest.ini

```<code>python_files = tests.py test_*.py */tests_*.py
</code>```

```<code>coverage run -m pytest
</code>```

Body:
I built django project with many applications. Now I want to generate a coverage report for these applications.  For testing purposes, I use py.test, pytest-django and pytest-cov.  So far, I can generate the report only by typing all my app names manually on the command line:

py.test --cov-report html --cov=app1 --cov=app2 --cov=app3 --cov=app4 */tests.py

Does pytest-cov have a way to specify all the applications with a simple expression?

Body:
Before

After

Change this line in pytest.ini

python_files = tests.py test_*.py */tests_*.py

coverage run -m pytest


问:
How to return 2 function calls in the arrow function at once?
Is there way to return 2 items in the same return of the arrow function?

```<code>useEffect(() => {
        return () =>
            removeEventListener('scroll', handleScroll) and setName('');
    }, []);
</code>```

Please don't offer using useEffect twice

答:
This should help</p>
```<code>useEffect(() => {
   return () => {
     removeEventListener('scroll', handleScroll);
     setName('');
 }
}, []);
</code>```

Body:
Is there way to return 2 items in the same return of the arrow function?

useEffect(() => {
        return () =>
            removeEventListener('scroll', handleScroll) and setName('');
    }, []);

Please don't offer using useEffect twice

Body:
This should help

useEffect(() => {
   return () => {
     removeEventListener('scroll', handleScroll);
     setName('');
 }
}, []);


问:
Serialize JSON from object to string / DateOnly
I have a JSON call from an object:

```<code> public record SaveDate(DateOnly StartDate, string EndDate, Object[] objects);
</code>```
```<code>var saveDate= new SaveDate(DateOnly.MinValue, DateTime.MaxValue.ToString("yyyy-MM-dd"),
new Object[] { objects});
</code>```

that when executes the API call it ends up returning

```<code>{
    "startDate": {
        "year": 1,
        "month": 1,
        "day": 1,
        "dayOfWeek": 1,
        "dayOfYear": 1,
        "dayNumber": 0
    },
    "endDate": "2022-07-07",
    "Object": [
        {
            "foo": "bar"
                }
            ]
        }
    ]
}
</code>```

however I need to have the format sent from startDate to be the same as endDate ("yyyy-MM-dd")  instead of the deserialized version. how can I do that?

note: I'm using DateOnly as type (.net 6.0) and the API expects a string in the format specified above.

答:
DateOnly and TimeOnly binding is not fully supported yet. You can implement your own converter for this type:

```<code>public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
    private const string Format = "yyyy-MM-dd";

    public override DateOnly ReadJson(JsonReader reader,
        Type objectType,
        DateOnly existingValue,
        bool hasExistingValue,
        JsonSerializer serializer) =>
        DateOnly.ParseExact((string)reader.Value, Format, CultureInfo.InvariantCulture);

    public override void WriteJson(JsonWriter writer, DateOnly value, JsonSerializer serializer) =>
        writer.WriteValue(value.ToString(Format, CultureInfo.InvariantCulture));
}

class MyClass
{
    [JsonConverter(typeof(DateOnlyJsonConverter))]
    public DateOnly dt { get; set; }
}

// prints {"dt":"2021-01-01"}
Console.WriteLine(JsonConvert.SerializeObject(new MyClass{dt = new DateOnly(2021,1,1)}));
</code>```

For System.Text.Json - see this answer.

UPD

Recently released 13.0.2 version of Newtonsoft.Json supports DateOnly and TimeOnly:

13.0.2

New feature - Add support for DateOnly and TimeOnly

Body:
I have a JSON call from an object:

 public record SaveDate(DateOnly StartDate, string EndDate, Object[] objects);

var saveDate= new SaveDate(DateOnly.MinValue, DateTime.MaxValue.ToString("yyyy-MM-dd"),
new Object[] { objects});

that when executes the API call it ends up returning

{
    "startDate": {
        "year": 1,
        "month": 1,
        "day": 1,
        "dayOfWeek": 1,
        "dayOfYear": 1,
        "dayNumber": 0
    },
    "endDate": "2022-07-07",
    "Object": [
        {
            "foo": "bar"
                }
            ]
        }
    ]
}

however I need to have the format sent from startDate to be the same as endDate ("yyyy-MM-dd")  instead of the deserialized version. how can I do that?

note: I'm using DateOnly as type (.net 6.0) and the API expects a string in the format specified above.

Body:
DateOnly and TimeOnly binding is not fully supported yet. You can implement your own converter for this type:

public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
    private const string Format = "yyyy-MM-dd";

    public override DateOnly ReadJson(JsonReader reader,
        Type objectType,
        DateOnly existingValue,
        bool hasExistingValue,
        JsonSerializer serializer) =>
        DateOnly.ParseExact((string)reader.Value, Format, CultureInfo.InvariantCulture);

    public override void WriteJson(JsonWriter writer, DateOnly value, JsonSerializer serializer) =>
        writer.WriteValue(value.ToString(Format, CultureInfo.InvariantCulture));
}

class MyClass
{
    [JsonConverter(typeof(DateOnlyJsonConverter))]
    public DateOnly dt { get; set; }
}

// prints {"dt":"2021-01-01"}
Console.WriteLine(JsonConvert.SerializeObject(new MyClass{dt = new DateOnly(2021,1,1)}));

For System.Text.Json - see this answer.

UPD

Recently released 13.0.2 version of Newtonsoft.Json supports DateOnly and TimeOnly:

13.0.2

New feature - Add support for DateOnly and TimeOnly


问:
Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?
I am trying to understand what the benefits of using interfaces are so that I can know when and how to use them. Most sources on the internet are relatively surface-level, explaining how interfaces work but now why to use them, and when I look up the titular question, I don't get any results that tell me whether the purpose of interfaces extends beyond polymorphism and multiple inheritances.

My reasoning is that if an interface were inherited by only one class, it would be useless, and when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism, and the only thing that makes implementation different from extension is multiple inheritances.

If I knew for sure that their purpose was limited to this, I would have an increased confidence in my design decisions, and if I learned of a purpose outside of this, it would fill a serious gap in my knowledge. I have used the design patterns tag because there is perhaps a design pattern which makes use of interfaces in a way that is distinctly beyond mere polymorphism or multiple inheritances.

答:
if an interface were inherited by only one class, it would be useless

I agree, but you can read a lot of discussion on this topic in Java Interfaces Methodology: Should every class implement an interface?

when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism

I agree, it would be silly to implement an interface and then bypass it by invoking its methods directly on the concrete class. The purpose of implementing an interface is to have its abstract methods called, which is polymorphism in action. Since polymorphism is the primary tool of Object Oriented Programming, you could take this statement a step further and say that OOP makes no difference unless it is used for polymorphism.

the only thing that makes implementation different from extension is multiple inheritances

No, the primary difference between these Java constructs is that interface implementation facilitates stateless inheritance whereas class extension facilitates stateful inheritance. Java happens to support multiple stateless inheritance and single stateful inheritance. This dichotomy may be considered a mistake.

Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?

In practice, yes. You can find interfaces used for other purposes such as constant interfaces or marker interfaces. Whether these practices are advisable has been debated.


问:
Access session value in gatling checks
I use gatling to send data to an ActiveMQ. The payload is generated in a separate method. The response should also be validated. However, how can I access the session data within the checks
check(bodyString.is())  or  simpleCheck(...)? I have also thought about storing the current payload in a separate global variable, but I don't know if this is the right approach. My code's setup looks like this at the moment:

val scn = scenario("Example ActiveMQ Scenario")
  .exec(jms("Test").requestReply
    .queue(...)
    .textMessage{ session => val message = createPayload(); session.set("payload", payload); message}
    .check(simpleCheck{message => customCheck(message, ?????? )})) //access stored payload value, alternative: check(bodystring.is(?????)

def customCheck(m: Message, string: String) = {
 // check logic goes here
}
```

答:
Disclaimer: providing example in Java as you don't seem to be a Scala developper, so Java would be a better fit for you (supported since Gatling 3.7).

The way you want to do things can't possibly work.

.textMessage(session -> {
   String message = createPayload();
   session.set("payload", payload);
   return message;
  }
)
```
<p>As explained in the documentation, <code>Session</code> is immutable, so in a function that's supposed to return the payload, you can't also return a new Session.</p>
<p>What you would have to do it first store the payload in the session, then fetch it:</p>
<pre class="lang-java prettyprint-override"><code>.exec(session -> session.set("payload", createPayload()))
...
.textMessage("#{payload}")
</code>```

Regarding writing your check, simpleCheck doesn't have access to the Session. You have to use check(bodyString.is()) and pass a function to is, again as explained in the documentation.

Title: Access session value in gatling checks

Body:
Disclaimer: providing example in Java as you don't seem to be a Scala developper, so Java would be a better fit for you (supported since Gatling 3.7).

The way you want to do things can't possibly work.

.textMessage(session -> {
   String message = createPayload();
   session.set("payload", payload);
   return message;
  }
)

As explained in the documentation, Session is immutable, so in a function that's supposed to return the payload, you can't also return a new Session.

What you would have to do it first store the payload in the session, then fetch it:

.exec(session -> session.set("payload", createPayload()))
...
.textMessage("#{payload}")

Regarding writing your check, simpleCheck doesn't have access to the Session. You have to use check(bodyString.is()) and pass a function to is, again as explained in the documentation.


答:
just change your code to this:

```<code>useEffect(() => {
        return () => {
            removeEventListener('scroll', handleScroll);
            setName('');
        }
    }, []);
</code>```

But setting state on unMount is not suggested

Title: How to return 2 function calls in the arrow function at once?

Body:
just change your code to this:

useEffect(() => {
        return () => {
            removeEventListener('scroll', handleScroll);
            setName('');
        }
    }, []);

But setting state on unMount is not suggested