问:
Using .Net to deskew an image
I have been searching high and low for a reliable way to deskew an image in .Net, and am not having much luck.

At the minute I am using Aforge. This is a pain as I am working with WPF, so  the images I am working with are BitmapImage objects, as opposed to Bitmap objects, meaning I need to start with a BitmapImage object, save this to a memory stream, create a new Bitmap object from the memory stream, go through the deskewing process, save the deskewed image to a new memory stream and then create a new BitmapImage object from said memory stream. Not only that, but the deskewing isn't great.

I am trying to read OMR data of a piece of paper scanned into a scanner, and therefore I need to rely on a particular OMR box being at the same co-ordinates every time, so the deskewing needs to be reliable.

So I am using Aforge at the minute, I can't find any other free/open source libraries for image deskewing in .Net, everything I have found is either properly expensive or in C/C++.

My question is do other free/open source libraries exist that assist in image deskewing in .Net? If so what are they called, if not how should I approach this problem?

Edit: For example, let's say I have the below page:

Note: This is for illustrative purposes only, but the actual image does indeed have a black rectangle at each corner of the page, maybe this will help.

When I print this out, and scan it back into my scanner, it looks like this:

I need to deskew this image so that my box is in the same place each time. In the real world, there are a lot of boxes, they are smaller and close together, so the accuracy is important.

My current method for this is a massive ineffective pain-in-the-ass:

```<code>using AForge.Imaging;
using AForge.Imaging.Filters;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public static BitmapImage DeskewBitmap(BitmapImage skewedBitmap)
{
    //Using a memory stream to minimise disk IO
    var memoryStream = BitmapImageToMemoryStream(skewedBitmap);

    var bitmap = MemoryStreamToBitmap(memoryStream);
    var skewAngle = CalculateSkewAngle(bitmap);

    //Aforge needs a Bppp indexed image for the deskewing process
    var bitmapConvertedToBbppIndexed = ConvertBitmapToBbppIndexed(bitmap);

    var rotatedImage = DeskewBitmap(skewAngle, bitmapConvertedToBbppIndexed);

    //I need to convert the image back to a non indexed format to put it back into a BitmapImage object
    var imageConvertedToNonIndexed = ConvertImageToNonIndexed(rotatedImage);

    var imageAsMemoryStream = BitmapToMemoryStream(imageConvertedToNonIndexed);
    var memoryStreamAsBitmapImage = MemoryStreamToBitmapImage(imageAsMemoryStream);

    return memoryStreamAsBitmapImage;
}

private static Bitmap ConvertImageToNonIndexed(Bitmap rotatedImage)
{
    var imageConvertedToNonIndexed = rotatedImage.Clone(
        new Rectangle(0, 0, rotatedImage.Width, rotatedImage.Height), PixelFormat.Format32bppArgb);
    return imageConvertedToNonIndexed;
}

private static Bitmap DeskewBitmap(double skewAngle, Bitmap bitmapConvertedToBbppIndexed)
{
    var rotationFilter = new RotateBilinear(-skewAngle) { FillColor = Color.White };

    var rotatedImage = rotationFilter.Apply(bitmapConvertedToBbppIndexed);
    return rotatedImage;
}

private static double CalculateSkewAngle(Bitmap bitmapConvertedToBbppIndexed)
{
    var documentSkewChecker = new DocumentSkewChecker();

    double skewAngle = documentSkewChecker.GetSkewAngle(bitmapConvertedToBbppIndexed);

    return skewAngle;
}

private static Bitmap ConvertBitmapToBbppIndexed(Bitmap bitmap)
{
    var bitmapConvertedToBbppIndexed = bitmap.Clone(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format8bppIndexed);
    return bitmapConvertedToBbppIndexed;
}

private static BitmapImage ResizeBitmap(BitmapImage originalBitmap, int desiredWidth, int desiredHeight)
{
    var ms = BitmapImageToMemoryStream(originalBitmap);
    ms.Position = 0;

    var result = new BitmapImage();
    result.BeginInit();
    result.DecodePixelHeight = desiredHeight;
    result.DecodePixelWidth = desiredWidth;

    result.StreamSource = ms;
    result.CacheOption = BitmapCacheOption.OnLoad;

    result.EndInit();
    result.Freeze();

    return result;
}

private static MemoryStream BitmapImageToMemoryStream(BitmapImage image)
{
    var ms = new MemoryStream();

    var encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(image));

    encoder.Save(ms);

    return ms;
}

private static BitmapImage MemoryStreamToBitmapImage(MemoryStream ms)
{
    ms.Position = 0;
    var bitmap = new BitmapImage();

    bitmap.BeginInit();

    bitmap.StreamSource = ms;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;

    bitmap.EndInit();
    bitmap.Freeze();

    return bitmap;
}

private static Bitmap MemoryStreamToBitmap(MemoryStream ms)
{
    return new Bitmap(ms);
}

private static MemoryStream BitmapToMemoryStream(Bitmap image)
{
    var memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Bmp);

    return memoryStream;
}
</code>```

In retrospect, a couple more questions:

Am I using AForge correctly?

Is AForge the best library to use for this task?

How could my current approach to this be improved to get more accurate results?

答:
For those who end up here from google, deskewing can be done easily using the Magick.NET library.

Install one of the nuget packages, for example Magick.NET-Q16-AnyCPU.

Usage:

```<code>private byte[] DeskewImage(byte[] imageFileBytes)
{
    var img = new MagickImage(imageFileBytes);
    // ImageMagick docs say 40% should work for most images
    img.Deskew(new Percentage(40d));
    return img.ToByteArray();
}
</code>```

Title: Using .Net to deskew an image

Body:
I have been searching high and low for a reliable way to deskew an image in .Net, and am not having much luck.

At the minute I am using Aforge. This is a pain as I am working with WPF, so  the images I am working with are BitmapImage objects, as opposed to Bitmap objects, meaning I need to start with a BitmapImage object, save this to a memory stream, create a new Bitmap object from the memory stream, go through the deskewing process, save the deskewed image to a new memory stream and then create a new BitmapImage object from said memory stream. Not only that, but the deskewing isn't great.

I am trying to read OMR data of a piece of paper scanned into a scanner, and therefore I need to rely on a particular OMR box being at the same co-ordinates every time, so the deskewing needs to be reliable.

So I am using Aforge at the minute, I can't find any other free/open source libraries for image deskewing in .Net, everything I have found is either properly expensive or in C/C++.

My question is do other free/open source libraries exist that assist in image deskewing in .Net? If so what are they called, if not how should I approach this problem?

Edit: For example, let's say I have the below page:

Note: This is for illustrative purposes only, but the actual image does indeed have a black rectangle at each corner of the page, maybe this will help.

When I print this out, and scan it back into my scanner, it looks like this:

I need to deskew this image so that my box is in the same place each time. In the real world, there are a lot of boxes, they are smaller and close together, so the accuracy is important.

My current method for this is a massive ineffective pain-in-the-ass:

using AForge.Imaging;
using AForge.Imaging.Filters;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public static BitmapImage DeskewBitmap(BitmapImage skewedBitmap)
{
    //Using a memory stream to minimise disk IO
    var memoryStream = BitmapImageToMemoryStream(skewedBitmap);

    var bitmap = MemoryStreamToBitmap(memoryStream);
    var skewAngle = CalculateSkewAngle(bitmap);

    //Aforge needs a Bppp indexed image for the deskewing process
    var bitmapConvertedToBbppIndexed = ConvertBitmapToBbppIndexed(bitmap);

    var rotatedImage = DeskewBitmap(skewAngle, bitmapConvertedToBbppIndexed);

    //I need to convert the image back to a non indexed format to put it back into a BitmapImage object
    var imageConvertedToNonIndexed = ConvertImageToNonIndexed(rotatedImage);

    var imageAsMemoryStream = BitmapToMemoryStream(imageConvertedToNonIndexed);
    var memoryStreamAsBitmapImage = MemoryStreamToBitmapImage(imageAsMemoryStream);

    return memoryStreamAsBitmapImage;
}

private static Bitmap ConvertImageToNonIndexed(Bitmap rotatedImage)
{
    var imageConvertedToNonIndexed = rotatedImage.Clone(
        new Rectangle(0, 0, rotatedImage.Width, rotatedImage.Height), PixelFormat.Format32bppArgb);
    return imageConvertedToNonIndexed;
}

private static Bitmap DeskewBitmap(double skewAngle, Bitmap bitmapConvertedToBbppIndexed)
{
    var rotationFilter = new RotateBilinear(-skewAngle) { FillColor = Color.White };

    var rotatedImage = rotationFilter.Apply(bitmapConvertedToBbppIndexed);
    return rotatedImage;
}

private static double CalculateSkewAngle(Bitmap bitmapConvertedToBbppIndexed)
{
    var documentSkewChecker = new DocumentSkewChecker();

    double skewAngle = documentSkewChecker.GetSkewAngle(bitmapConvertedToBbppIndexed);

    return skewAngle;
}

private static Bitmap ConvertBitmapToBbppIndexed(Bitmap bitmap)
{
    var bitmapConvertedToBbppIndexed = bitmap.Clone(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format8bppIndexed);
    return bitmapConvertedToBbppIndexed;
}

private static BitmapImage ResizeBitmap(BitmapImage originalBitmap, int desiredWidth, int desiredHeight)
{
    var ms = BitmapImageToMemoryStream(originalBitmap);
    ms.Position = 0;

    var result = new BitmapImage();
    result.BeginInit();
    result.DecodePixelHeight = desiredHeight;
    result.DecodePixelWidth = desiredWidth;

    result.StreamSource = ms;
    result.CacheOption = BitmapCacheOption.OnLoad;

    result.EndInit();
    result.Freeze();

    return result;
}

private static MemoryStream BitmapImageToMemoryStream(BitmapImage image)
{
    var ms = new MemoryStream();

    var encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(image));

    encoder.Save(ms);

    return ms;
}

private static BitmapImage MemoryStreamToBitmapImage(MemoryStream ms)
{
    ms.Position = 0;
    var bitmap = new BitmapImage();

    bitmap.BeginInit();

    bitmap.StreamSource = ms;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;

    bitmap.EndInit();
    bitmap.Freeze();

    return bitmap;
}

private static Bitmap MemoryStreamToBitmap(MemoryStream ms)
{
    return new Bitmap(ms);
}

private static MemoryStream BitmapToMemoryStream(Bitmap image)
{
    var memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Bmp);

    return memoryStream;
}

In retrospect, a couple more questions:

Am I using AForge correctly?

Is AForge the best library to use for this task?

How could my current approach to this be improved to get more accurate results?

Body:
For those who end up here from google, deskewing can be done easily using the Magick.NET library.

Install one of the nuget packages, for example Magick.NET-Q16-AnyCPU.

Usage:

private byte[] DeskewImage(byte[] imageFileBytes)
{
    var img = new MagickImage(imageFileBytes);
    // ImageMagick docs say 40% should work for most images
    img.Deskew(new Percentage(40d));
    return img.ToByteArray();
}


来源: stackexchange

问:
Data from Three MySQL table to one master table
I have three customer tables:

example:

```<code>customers_1, customers_2, customers_3
</code>```

And want to create a new master table which will have ONLY the LATEST UPDATED record of a single customer.

One customer can have 1 record in all three tables.
One customer can have multiple records in all three tables.
One customer can have ONLY 1 record in any one table.

```<code>'mobile_no' is used to identify uniqueness.
'updated_at' is used to know the latest record.
</code>```

I am going to write it in PHP. I just want to know what is the best approach.

Note: Assume that one table (say customers_1) will always have more records than the other two.
Example:

```<code>customers_1: 500000 records
customers_2: 250000 records
customers_3: 220000 records
</code>```

答:
You can use UNION to aggregate the three tables into one, and then query the most recet record of each customer

something like this should do the work:

```<code>WITH all_customers AS (
  SELECT *
  FROM customers_1
  UNION
  SELECT *
  FROM customers_2
  UNION
  SELECT *
  FROM customers_3
    )
SELECT ac.*
FROM (
  SELECT mobile_no, MAX(updated_at) as latest_date
  FROM all_customers) latest
LEFT JOIN all_customers ac
ON ac.mobile_no = latest.mobile_no AND ac.updated_at = latest.latest_date
</code>```

and if you want to use this query frequently you can create a view

```<code>CREATE VIEW latest_customers AS
-- enter query here
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three customer tables:

example:

customers_1, customers_2, customers_3

And want to create a new master table which will have ONLY the LATEST UPDATED record of a single customer.

One customer can have 1 record in all three tables.
One customer can have multiple records in all three tables.
One customer can have ONLY 1 record in any one table.

'mobile_no' is used to identify uniqueness.
'updated_at' is used to know the latest record.

I am going to write it in PHP. I just want to know what is the best approach.

Note: Assume that one table (say customers_1) will always have more records than the other two.
Example:

customers_1: 500000 records
customers_2: 250000 records
customers_3: 220000 records

Body:
You can use UNION to aggregate the three tables into one, and then query the most recet record of each customer

something like this should do the work:

WITH all_customers AS (
  SELECT *
  FROM customers_1
  UNION
  SELECT *
  FROM customers_2
  UNION
  SELECT *
  FROM customers_3
    )
SELECT ac.*
FROM (
  SELECT mobile_no, MAX(updated_at) as latest_date
  FROM all_customers) latest
LEFT JOIN all_customers ac
ON ac.mobile_no = latest.mobile_no AND ac.updated_at = latest.latest_date

and if you want to use this query frequently you can create a view

CREATE VIEW latest_customers AS
-- enter query here


问:
How to create proxy object at runtime using LambdaMetaFactory?
How can I create proxy objects for SAM/functional interfaces using LambdaMetaFactory

ie. equivalent of
public static Object java.lang.reflect.Proxy.newProxyInstance(ClassLoader, Class<?>[], InvocationHandler)

Eg. I have multiple factory interfaces

```<code>interface X{
// members
// methods
}

interface Y{
// members
// methods
}
public interface Factory1{
  X get(String name);
}
public interface Factory2{
Y get(String name);
}
.
.
.
public interface FactoryN{
someclassOrInterface get(String name);
}
</code>```

and I want to generate the factory proxies at runtime tied  to some prebuilt bean container
e.g.

```<code>public Object getFactoryBean(String name){
return beanContainer.get(name);
}
</code>```

something similar  to

```<code>org.springframework.beans.factory.config.ServiceLocatorFactoryBean
</code>```

but built on LambdaMetaFactory. I tried following code but gets an exception

```<code>static <T> T  getFactory(Class<T> factoryClass) {
    T factory =null;
    try {
    final MethodHandles.Lookup lookup = MethodHandles.lookup();
    Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
    final CallSite site = LambdaMetafactory.metafactory(lookup,
                    "get",
                    MethodType.methodType(factoryClass, String.class),
                    MethodType.methodType(beanType),
                    lookup.findStatic(ReflectionUtil.class, "getFactoryBean", MethodType.methodType(Object.class, String.class)),
                    MethodType.methodType(beanType));
    factory = (T) site.getTarget().invoke();
    } catch(Throwable e) {
      e.printStackTrace();
    }
    return factory;
}
 public static Object getFactoryBean(String beanName) {
     return beanMap.get(beanName);
  }
</code>```

```<code>java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(String)Factory1 to ()Object
    at java.lang.invoke.MethodHandle.asTypeUncached(MethodHandle.java:775)
    at java.lang.invoke.MethodHandle.asType(MethodHandle.java:761)
    at java.lang.invoke.Invokers.checkGenericType(Invokers.java:321)
</code>```

Thanks in advance.

答:
Your code specifies a String argument for the invokedType argument instead of the samMethodType and instantiatedMethodType arguments. This would be the right thing if you want to capture a String value and implement a functional signature without arguments.

But you consistently show interfaces with a String argument and call invoke() without arguments. Therefore, the code should look like

```<code>static <T> T getFactory(Class<T> factoryClass) {
    T factory =null;
    try {
        final MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
        final CallSite site = LambdaMetafactory.metafactory(lookup,
                        "get",
                        MethodType.methodType(factoryClass),
                        MethodType.methodType(beanType, String.class),
                        lookup.findStatic(ReflectionUtil.class, "getFactoryBean",
                            MethodType.methodType(Object.class, String.class)),
                        MethodType.methodType(beanType, String.class));
        factory = (T)site.getTarget().invoke();
    } catch(Throwable e) {
      e.printStackTrace();
    }
    return factory;
}
</code>```

which can be simplified to

```<code>static <T> T getFactory(Class<T> factoryClass) {
    try {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
        MethodHandle target = lookup.findStatic(ReflectionUtil.class, "getFactoryBean",
            MethodType.methodType(Object.class, String.class));
        MethodType funcType = target.type().changeReturnType(beanType);
        return (T)LambdaMetafactory.metafactory(
            lookup, "get", MethodType.methodType(factoryClass), funcType, target, funcType)
            .getTarget().invoke();
    } catch(Throwable e) {
      e.printStackTrace();
      return null; // rethink this error handling
    }
}
</code>```

Body:
How can I create proxy objects for SAM/functional interfaces using LambdaMetaFactory

ie. equivalent of
public static Object java.lang.reflect.Proxy.newProxyInstance(ClassLoader, Class<?>[], InvocationHandler)

Eg. I have multiple factory interfaces

interface X{
// members
// methods
}

interface Y{
// members
// methods
}
public interface Factory1{
  X get(String name);
}
public interface Factory2{
Y get(String name);
}
.
.
.
public interface FactoryN{
someclassOrInterface get(String name);
}

and I want to generate the factory proxies at runtime tied  to some prebuilt bean container
e.g.

public Object getFactoryBean(String name){
return beanContainer.get(name);
}

something similar  to

org.springframework.beans.factory.config.ServiceLocatorFactoryBean

but built on LambdaMetaFactory. I tried following code but gets an exception

static <T> T  getFactory(Class<T> factoryClass) {
    T factory =null;
    try {
    final MethodHandles.Lookup lookup = MethodHandles.lookup();
    Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
    final CallSite site = LambdaMetafactory.metafactory(lookup,
                    "get",
                    MethodType.methodType(factoryClass, String.class),
                    MethodType.methodType(beanType),
                    lookup.findStatic(ReflectionUtil.class, "getFactoryBean", MethodType.methodType(Object.class, String.class)),
                    MethodType.methodType(beanType));
    factory = (T) site.getTarget().invoke();
    } catch(Throwable e) {
      e.printStackTrace();
    }
    return factory;
}
 public static Object getFactoryBean(String beanName) {
     return beanMap.get(beanName);
  }

java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(String)Factory1 to ()Object
    at java.lang.invoke.MethodHandle.asTypeUncached(MethodHandle.java:775)
    at java.lang.invoke.MethodHandle.asType(MethodHandle.java:761)
    at java.lang.invoke.Invokers.checkGenericType(Invokers.java:321)

Thanks in advance.

Body:
Your code specifies a String argument for the invokedType argument instead of the samMethodType and instantiatedMethodType arguments. This would be the right thing if you want to capture a String value and implement a functional signature without arguments.

But you consistently show interfaces with a String argument and call invoke() without arguments. Therefore, the code should look like

static <T> T getFactory(Class<T> factoryClass) {
    T factory =null;
    try {
        final MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
        final CallSite site = LambdaMetafactory.metafactory(lookup,
                        "get",
                        MethodType.methodType(factoryClass),
                        MethodType.methodType(beanType, String.class),
                        lookup.findStatic(ReflectionUtil.class, "getFactoryBean",
                            MethodType.methodType(Object.class, String.class)),
                        MethodType.methodType(beanType, String.class));
        factory = (T)site.getTarget().invoke();
    } catch(Throwable e) {
      e.printStackTrace();
    }
    return factory;
}

which can be simplified to

static <T> T getFactory(Class<T> factoryClass) {
    try {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class<?> beanType = factoryClass.getMethod("get", String.class).getReturnType();
        MethodHandle target = lookup.findStatic(ReflectionUtil.class, "getFactoryBean",
            MethodType.methodType(Object.class, String.class));
        MethodType funcType = target.type().changeReturnType(beanType);
        return (T)LambdaMetafactory.metafactory(
            lookup, "get", MethodType.methodType(factoryClass), funcType, target, funcType)
            .getTarget().invoke();
    } catch(Throwable e) {
      e.printStackTrace();
      return null; // rethink this error handling
    }
}


问:
Is there any way to get live telemetry data from the DJI Mavic 2 Zoom to another unit, say a computer?
As part of a course on my university we've been given the task of taking the live wind telemetry from a drone and then feeding it to a neural network so that it gives better estimates than just using a sensor.

The research we've concluded so far tells us that our drone, the DJI Mavic 2 Zoom, is only compatible with the Windows SDK but not the onboard SDK.

Simply our question is; is there any way for us to send the raw wind speed and direction data from the drones sensors to a computer?

答:
The SDK only provides the wind warning level(0, 1 and 2). It does not provide any information regarding the direction from which the wind is blowing or the actual speed of the wind.

The aircraft tries to stay in it's current position on it's own, even if there is moderate wind blowing. However the drone does not tell the user how much it has to work in which direction to negate the effect of the wind.

I assume you're better off with accessing real time wind information for your position from a weather service on the internet, if that's available in your country.


问:
How to set the global variable in a function for cmake?
I'm writing a CMakeLists.txt to generate files and compile the generated files. I create a function to add some file path strings to a global list variable.

My CMakeLists.txt:

```<code>set(source_list "nothing")
function(test file_path)
    list(APPEND source_list ${file_path})
endfunction(test)
test(abc.txt)
test(def.txt)
message("At last, the source_list is:\"${source_list}\"")
</code>```

The cmake output:

```<code>At last, the source_list is:"nothing"
</code>```

Someone suggested that to use macro instead of function, but I do need use local variable, so I need to use the function instead of macro.

How can I correctly set the global variable source_list in the function test()? Can't cmake do it in a simple and normal way?

答: Another way to address this issue is using macro instead of function - this way all variables inside macro will be evaluated in context of caller.

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a CMakeLists.txt to generate files and compile the generated files. I create a function to add some file path strings to a global list variable.

My CMakeLists.txt:

set(source_list "nothing")
function(test file_path)
    list(APPEND source_list ${file_path})
endfunction(test)
test(abc.txt)
test(def.txt)
message("At last, the source_list is:\"${source_list}\"")

The cmake output:

At last, the source_list is:"nothing"

Someone suggested that to use macro instead of function, but I do need use local variable, so I need to use the function instead of macro.

How can I correctly set the global variable source_list in the function test()? Can't cmake do it in a simple and normal way?


问:
How to edit values in MySQL Workbench directly?
I am using MySQL Workbench to manage a database, and I am unable to edit values in the database directly. When I click on a cell/value and choose "Open Value in Editor" and I change the text and click apply, the change doesn't persist. Would anyone know of the reason/solution to this?</p>

答: Once you are finished with editing the individual values in the result grid, you have to apply your changes to the DB:


问:
Named Query with List of object as input using JPA named query
Getting below QueryExecutionRequestException when I try to excecute update Named query using JPA repository.

```<code>org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.company.farmer.entity.FarmProducts p set p.isDeleted=:isDeleted where p.productId IN (:productIdsList_0, :productIdsList_1)]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.company.farmer.entity.FarmProducts p set p.isDeleted=:isDeleted where p.productId IN (:productIdsList_0, :productIdsList_1)]
</code>```

Code:

```<code>@Repository
public interface FarmProductRepository extends JpaRepository<FarmProducts, Long> {

void deleteProduct(@Param("isDeleted") String isDeleted, @Param("productIdsList") List<Long> productIdsList);

}

@Override
public String deleteProductAndCategory(long categoryId, FarmProductIdsDTO farmProductIds) {
    farmProductRepository.deleteProduct(FarmerProductCategoryConstants.DELETE_YES_FLAG, farmProductIds.getFarmProductIds());

    return FarmerProductCategoryConstants.SUCCESS;
}

@Entity
@Table(name="farm_products")
@Getter
@Setter
@ToString(exclude= "productCategory")
@NoArgsConstructor
@AllArgsConstructor
@NamedQueries({@NamedQuery(name="FarmProducts.deleteProduct", query="update FarmProducts p set p.isDeleted=:isDeleted where p.productId IN (:productIdsList)") })
public class FarmProducts extends BaseModel {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FARM_PRODUCT_GENERATOR")
    @SequenceGenerator(name = "FARM_PRODUCT_GENERATOR", sequenceName = "FARM_PRODUCT_GENERATOR_SEQ", allocationSize = 1)
    @Column(name = "farm_product_id")
    public Long productId;

    @ManyToOne
    @JoinColumn(name = "farm_product_category_id")
    @JsonIgnoreProperties("products")
    public ProductCategory productCategory;

    @Column(name = "product_name")
    public String product;

    @Column(name = "is_deleted")
    public String isDeleted;

}
</code>```

I am trying to pass a list of productId to make the isDeleted as "N". But update functionality fails because of the QueryExecutionRequestException.

答:
By default Spring Data treats all queries as SELECT statements. If you have an UPDATE (or DELETE) statement you have you have to apply de @Modifying annotation on the query.
See https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.modifying-queries

Body:
Getting below QueryExecutionRequestException when I try to excecute update Named query using JPA repository.

org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.company.farmer.entity.FarmProducts p set p.isDeleted=:isDeleted where p.productId IN (:productIdsList_0, :productIdsList_1)]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.company.farmer.entity.FarmProducts p set p.isDeleted=:isDeleted where p.productId IN (:productIdsList_0, :productIdsList_1)]

Code:

@Repository
public interface FarmProductRepository extends JpaRepository<FarmProducts, Long> {

void deleteProduct(@Param("isDeleted") String isDeleted, @Param("productIdsList") List<Long> productIdsList);

}

@Override
public String deleteProductAndCategory(long categoryId, FarmProductIdsDTO farmProductIds) {
    farmProductRepository.deleteProduct(FarmerProductCategoryConstants.DELETE_YES_FLAG, farmProductIds.getFarmProductIds());

    return FarmerProductCategoryConstants.SUCCESS;
}

@Entity
@Table(name="farm_products")
@Getter
@Setter
@ToString(exclude= "productCategory")
@NoArgsConstructor
@AllArgsConstructor
@NamedQueries({@NamedQuery(name="FarmProducts.deleteProduct", query="update FarmProducts p set p.isDeleted=:isDeleted where p.productId IN (:productIdsList)") })
public class FarmProducts extends BaseModel {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FARM_PRODUCT_GENERATOR")
    @SequenceGenerator(name = "FARM_PRODUCT_GENERATOR", sequenceName = "FARM_PRODUCT_GENERATOR_SEQ", allocationSize = 1)
    @Column(name = "farm_product_id")
    public Long productId;

    @ManyToOne
    @JoinColumn(name = "farm_product_category_id")
    @JsonIgnoreProperties("products")
    public ProductCategory productCategory;

    @Column(name = "product_name")
    public String product;

    @Column(name = "is_deleted")
    public String isDeleted;

}

I am trying to pass a list of productId to make the isDeleted as "N". But update functionality fails because of the QueryExecutionRequestException.


问:
How to handle QPropertyAnimation for a large number of widgets
I want to have many colored dots constantly move across a background. (Description of code below): A PolkaDot widget is constructed with a random color, size, position, and duration. The QPropertyAnimation moves the widget across the screen from left to right, restarting at a new height when the animation ends. 100 PolkaDot widgets are constructed in the Background widget, which is enough to make it appear like tons of new dots are constantly rushing in from the left side of the screen. </p>

<p>However, the 100 property animations seem to consume a lot of CPU power, causing it to slow down and look un-smooth. Is there another way to achieve a similar result? Try running the code below. </p>

```<code>import sys, random
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

colors = [QColor('#f00'), QColor('#00f'), QColor('#0f0'), QColor('#ff0'),
          QColor('#fff'), QColor('#ff6000'), QColor('#6b00ff'), QColor('#f0f')]

class PolkaDot(QWidget):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setFixedSize(50, 50)
        self.color = random.choice(colors)
        self.r = random.randrange(5, 22)
        self.move(random.randrange(w), random.randrange(h))
        self.anim = QPropertyAnimation(self, b'pos')
        self.anim.finished.connect(self.run)
        self.anim.setDuration(random.randrange(3000, 9000))
        self.anim.setStartValue(QPoint(self.x() - (w + 60), self.y()))
        self.anim.setEndValue(QPoint(w + 60, self.y()))
        self.anim.start()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)
        qp.setBrush(self.color)
        qp.setPen(QPen(self.color.darker(130), self.r / 5))
        qp.drawEllipse(QPoint(25, 25), self.r, self.r)

    def run(self):
        y = random.randrange(h)
        self.anim.setDuration(random.randrange(3000, 9000))
        self.anim.setStartValue(QPoint(-60, y))
        self.anim.setEndValue(QPoint(w + 60, y + random.randrange(-50, 50)))
        self.anim.start()

class Background(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(window)
        polka_dots = [PolkaDot(self) for i in range(100)]
        self.setStyleSheet('background-color: #000')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QDesktopWidget().availableGeometry()
    w, h = window.width(), window.height()
    gui = Background()
    gui.show()
    sys.exit(app.exec_())
</code>```

答:
I sort of found a solution. For some reason, creating the dots in the background widget's paint event and calling repaint() on QTimer.timeout() to update the XY coordinates is much more efficient than using QPropertyAnimation. </p>

```<code>tick = 24

class Dot(object):

    def __init__(self):
        self.x = random.randrange(-w - 60, 0)
        self.randomize()

    def randomize(self):
        self.color = random.choice(colors)
        self.r = random.randrange(5, 22)
        self.y = random.randrange(h)
        self.x_speed = random.randrange(3000, 9000)
        self.y_speed = random.randrange(-50, 50)

    def move(self):
        self.x += w * tick / self.x_speed
        self.y += self.y_speed * tick / self.x_speed
        if self.x > w:
            self.x = -60
            self.randomize()

class Background(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(window)
        self.setStyleSheet('background-color: #000')
        self.dots = [Dot() for i in range(150)]
        self.timer = QTimer()
        self.timer.setInterval(tick)
        self.timer.timeout.connect(self.animate)
        self.timer.start()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)
        for dot in self.dots:
            qp.setBrush(dot.color)
            qp.setPen(QPen(dot.color.darker(130), dot.r / 5))
            qp.drawEllipse(QPoint(dot.x, dot.y), dot.r, dot.r)

    def animate(self):
        for d in self.dots:
            d.move()
        self.repaint()
</code>```

Body:
I want to have many colored dots constantly move across a background. (Description of code below): A PolkaDot widget is constructed with a random color, size, position, and duration. The QPropertyAnimation moves the widget across the screen from left to right, restarting at a new height when the animation ends. 100 PolkaDot widgets are constructed in the Background widget, which is enough to make it appear like tons of new dots are constantly rushing in from the left side of the screen.

However, the 100 property animations seem to consume a lot of CPU power, causing it to slow down and look un-smooth. Is there another way to achieve a similar result? Try running the code below.

import sys, random
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

colors = [QColor('#f00'), QColor('#00f'), QColor('#0f0'), QColor('#ff0'),
          QColor('#fff'), QColor('#ff6000'), QColor('#6b00ff'), QColor('#f0f')]

class PolkaDot(QWidget):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setFixedSize(50, 50)
        self.color = random.choice(colors)
        self.r = random.randrange(5, 22)
        self.move(random.randrange(w), random.randrange(h))
        self.anim = QPropertyAnimation(self, b'pos')
        self.anim.finished.connect(self.run)
        self.anim.setDuration(random.randrange(3000, 9000))
        self.anim.setStartValue(QPoint(self.x() - (w + 60), self.y()))
        self.anim.setEndValue(QPoint(w + 60, self.y()))
        self.anim.start()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)
        qp.setBrush(self.color)
        qp.setPen(QPen(self.color.darker(130), self.r / 5))
        qp.drawEllipse(QPoint(25, 25), self.r, self.r)

    def run(self):
        y = random.randrange(h)
        self.anim.setDuration(random.randrange(3000, 9000))
        self.anim.setStartValue(QPoint(-60, y))
        self.anim.setEndValue(QPoint(w + 60, y + random.randrange(-50, 50)))
        self.anim.start()

class Background(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(window)
        polka_dots = [PolkaDot(self) for i in range(100)]
        self.setStyleSheet('background-color: #000')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QDesktopWidget().availableGeometry()
    w, h = window.width(), window.height()
    gui = Background()
    gui.show()
    sys.exit(app.exec_())

Body:
I sort of found a solution. For some reason, creating the dots in the background widget's paint event and calling repaint() on QTimer.timeout() to update the XY coordinates is much more efficient than using QPropertyAnimation.

tick = 24

class Dot(object):

    def __init__(self):
        self.x = random.randrange(-w - 60, 0)
        self.randomize()

    def randomize(self):
        self.color = random.choice(colors)
        self.r = random.randrange(5, 22)
        self.y = random.randrange(h)
        self.x_speed = random.randrange(3000, 9000)
        self.y_speed = random.randrange(-50, 50)

    def move(self):
        self.x += w * tick / self.x_speed
        self.y += self.y_speed * tick / self.x_speed
        if self.x > w:
            self.x = -60
            self.randomize()

class Background(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(window)
        self.setStyleSheet('background-color: #000')
        self.dots = [Dot() for i in range(150)]
        self.timer = QTimer()
        self.timer.setInterval(tick)
        self.timer.timeout.connect(self.animate)
        self.timer.start()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)
        for dot in self.dots:
            qp.setBrush(dot.color)
            qp.setPen(QPen(dot.color.darker(130), dot.r / 5))
            qp.drawEllipse(QPoint(dot.x, dot.y), dot.r, dot.r)

    def animate(self):
        for d in self.dots:
            d.move()
        self.repaint()


问:
How to convert xelement to a string in c#?
I have an error like

== cannot be applied to operands of type string and xelement

.Here I am comparing

```<code>item.Element("APINumber").Value == apiitem
</code>```

which gives error. Can anyone help to correct this error by doing any conversion or something

```<code>var apilist = from first in txrrc
              join second in drill
              on first.Element("APINumber").Value
              equals second.Element("APINumber").Value
                           select first;
IEnumerable<XElement> items = from item in xml2.Descendants()
                .Elements("DrillingPermit")
                where item.Element("APINumber").Value == apiitem
                select (XElement)item;
</code>```

答:
Just a guess here as I don't know the apiitem type though since .Value is string, then the type is XElement

```<code>item.Element("APINumber").Value == apiitem.Value
</code>```

Body:
I have an error like

== cannot be applied to operands of type string and xelement

.Here I am comparing

item.Element("APINumber").Value == apiitem

which gives error. Can anyone help to correct this error by doing any conversion or something

var apilist = from first in txrrc
              join second in drill
              on first.Element("APINumber").Value
              equals second.Element("APINumber").Value
                           select first;
IEnumerable<XElement> items = from item in xml2.Descendants()
                .Elements("DrillingPermit")
                where item.Element("APINumber").Value == apiitem
                select (XElement)item;

Body:
Just a guess here as I don't know the apiitem type though since .Value is string, then the type is XElement

item.Element("APINumber").Value == apiitem.Value


问:
Cast a list into a list of objects in dart
the code below makes a rest call to a node.js server, which returns a json containing a series of values these values must be inserted in a list by casting the values in a Cantiere type object. How can I go about doing this?
What I want to do is convert every single json into a construction-type object and then insert them in a list.

JSON Call Flutter:

```<code>      static Future<List> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
          String RagioneSociale, bool isUtente) async {
        var ret;
        Map map = {
          'IdUtente': u.GetIdUtente(),
          'IdCantiere': IdCantiere,
          'NomeCantiere': "a",
          'RagioneSociale': RagioneSociale,
          'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
        };
        String value = await apiRequest("/cantieri/ricerca", map);

//The ret variable holds the json, what I want to do is create a list of Cantiere type objects.
        ret = json.decode(value);
        return (ret as Iterable<dynamic> ?? const <dynamic>[])
    .map((dynamic jsonObject) => Cantiere(
          new Cliente(
              jsonObject["IdCliente"] as int,
              jsonObject["RagioneSociale"] as String,
              jsonObject["Filiale"] as String,),
          jsonObject["IdCantiere"] as int,
          jsonObject["NomeCantiere"] as String,
          jsonObject["DescrizioneEstesa"] as String,
          jsonObject["Tipologia"] as String,
          jsonObject["Stato"] as String,
          jsonObject["StatoFatturazione"] as String,
          jsonObject["DataCreazione"] as String,
        ))
    .toList();
      }
</code>```

Cantiere.dart and Cliente.dart

```<code>    class Cliente {
          int _IdCliente;
          String _RagioneSociale;
          String _Filiale;
          Cliente(this._IdCliente, this._RagioneSociale, this._Filiale);

          String GetRagioneSociale() {
            return this._RagioneSociale;
          }
        }
            //Classe che rappresenta il cantiere
class Cantiere {

  String _NomeCantiere,
      _Tipologia,
      _Stato,
      _StatoFatturazione,
      _DescrizioneEstesa,
      _DataCreazione;
  int _IdCantiere;
  Cliente _c;

  Cantiere(
      this._c,
      this._IdCantiere,
      this._NomeCantiere,
      this._DescrizioneEstesa,
      this._Tipologia,
      this._Stato,
      this._StatoFatturazione,
      this._DataCreazione);

            }
</code>```

JSON Example:

```<code>[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "Ca asas",
        "NomeCantiere": "sala dd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "asasas"
    },

        "IdCantiere": 5,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "Ca asas",
        "NomeCantiere": "sala dd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "asasas"
    }

]
</code>```

答:
What jsonDecode does is actually converting a JSON string into a sequence of Lists and Maps with included primitive types, depending on the fact if it is a JSON array or JSON object or a JSON primitive.

So, the type of the output (based on the JSON snippet provided) is List which contains a number of Maps (but it is not to say that the type really is List<Map>).

What is necessary to get the wanted result is to map every JSON object from the decoded JSON to the needed object type:

```<code>return (ret as Iterable<dynamic> ?? const <dynamic>[])
  .map((dynamic jsonObject) =>
    Cliente(
      jsonObject["IdCliente"] as int,
      jsonObject["RagioneSociale"] as String,
      jsonObject["Filiale"] as String,
    )
  )
  .toList();
</code>```

Body:
the code below makes a rest call to a node.js server, which returns a json containing a series of values these values must be inserted in a list by casting the values in a Cantiere type object. How can I go about doing this?
What I want to do is convert every single json into a construction-type object and then insert them in a list.

JSON Call Flutter:

      static Future<List> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
          String RagioneSociale, bool isUtente) async {
        var ret;
        Map map = {
          'IdUtente': u.GetIdUtente(),
          'IdCantiere': IdCantiere,
          'NomeCantiere': "a",
          'RagioneSociale': RagioneSociale,
          'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
        };
        String value = await apiRequest("/cantieri/ricerca", map);

//The ret variable holds the json, what I want to do is create a list of Cantiere type objects.
        ret = json.decode(value);
        return (ret as Iterable<dynamic> ?? const <dynamic>[])
    .map((dynamic jsonObject) => Cantiere(
          new Cliente(
              jsonObject["IdCliente"] as int,
              jsonObject["RagioneSociale"] as String,
              jsonObject["Filiale"] as String,),
          jsonObject["IdCantiere"] as int,
          jsonObject["NomeCantiere"] as String,
          jsonObject["DescrizioneEstesa"] as String,
          jsonObject["Tipologia"] as String,
          jsonObject["Stato"] as String,
          jsonObject["StatoFatturazione"] as String,
          jsonObject["DataCreazione"] as String,
        ))
    .toList();
      }

Cantiere.dart and Cliente.dart

    class Cliente {
          int _IdCliente;
          String _RagioneSociale;
          String _Filiale;
          Cliente(this._IdCliente, this._RagioneSociale, this._Filiale);

          String GetRagioneSociale() {
            return this._RagioneSociale;
          }
        }
            //Classe che rappresenta il cantiere
class Cantiere {

  String _NomeCantiere,
      _Tipologia,
      _Stato,
      _StatoFatturazione,
      _DescrizioneEstesa,
      _DataCreazione;
  int _IdCantiere;
  Cliente _c;

  Cantiere(
      this._c,
      this._IdCantiere,
      this._NomeCantiere,
      this._DescrizioneEstesa,
      this._Tipologia,
      this._Stato,
      this._StatoFatturazione,
      this._DataCreazione);

            }

JSON Example:

[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "Ca asas",
        "NomeCantiere": "sala dd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "asasas"
    },

        "IdCantiere": 5,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "Ca asas",
        "NomeCantiere": "sala dd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "asasas"
    }

]

Body:
What jsonDecode does is actually converting a JSON string into a sequence of Lists and Maps with included primitive types, depending on the fact if it is a JSON array or JSON object or a JSON primitive.

So, the type of the output (based on the JSON snippet provided) is List which contains a number of Maps (but it is not to say that the type really is List<Map>).

What is necessary to get the wanted result is to map every JSON object from the decoded JSON to the needed object type:

return (ret as Iterable<dynamic> ?? const <dynamic>[])
  .map((dynamic jsonObject) =>
    Cliente(
      jsonObject["IdCliente"] as int,
      jsonObject["RagioneSociale"] as String,
      jsonObject["Filiale"] as String,
    )
  )
  .toList();


问:
How to implement class constants?
In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."

I find myself in need to clearly indicate in code that a property should not be changed.  I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?

I'm currently using a read-only property, but I wonder if there is a better way:

```<code>get MY_CONSTANT():number {return 10};
</code>```

I'm using typescript 1.8. Suggestions?

PS: I'm now using typescript 2.0.3, so I've accepted David's answer

答:
For me none of earlier answer works. I did need to convert my static class to enum.
Like this:

```<code>export enum MyConstants {
  MyFirstConstant = 'MyFirstConstant',
  MySecondConstant = 'MySecondConstant'
}
</code>```

Then in my component I add new property as suggested in other answers

```<code>export class MyComponent {
public MY_CONTANTS = MyConstans;
constructor() { }
}
</code>```

Then in my component's template I use it this way

```<code><div [myDirective]="MY_CONTANTS.MyFirstConstant"> </div>
</code>```

EDIT: Sorry. My problem was different than OP's. I still leave this here if someelse have same problem than I.

Title: How to implement class constants?

Body:
In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."

I find myself in need to clearly indicate in code that a property should not be changed.  I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?

I'm currently using a read-only property, but I wonder if there is a better way:

get MY_CONSTANT():number {return 10};

I'm using typescript 1.8. Suggestions?

PS: I'm now using typescript 2.0.3, so I've accepted David's answer

Body:
For me none of earlier answer works. I did need to convert my static class to enum.
Like this:

export enum MyConstants {
  MyFirstConstant = 'MyFirstConstant',
  MySecondConstant = 'MySecondConstant'
}

Then in my component I add new property as suggested in other answers

export class MyComponent {
public MY_CONTANTS = MyConstans;
constructor() { }
}

Then in my component's template I use it this way

<div [myDirective]="MY_CONTANTS.MyFirstConstant"> </div>

EDIT: Sorry. My problem was different than OP's. I still leave this here if someelse have same problem than I.


问:
calling a template function of a derived class
I'm having a problem in C++ with calling a function of a derived class while having a pointer to the base class.

EDIT:
Some answers referred me to CRTP

but my point is that I need to have a pointer to the "Base*" class not "Base*" because I'm unaware of the type currently being handled (The current instance is created from some sort of a factory).

Classes:

```<code>class Base
{
..
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};
</code>```

Usage:

```<code>int main()
{
   Base* BasePtr = new Derived1();

   // The expected function to be called is Derived1::func<int>()
   BasePtr->func<int>();

   return 0; // :)
}
</code>```

I can't make func virtual because the language does not support virtual template function.

It is only allowed if only the class is have template arguments but not if the function within it has template arguments.

I have seen a similar problem resolved within Boost.Serialization but couldn't understand the solution.

Thanks,

Koby Meir

答:
The two existing solutions trade dynamic polymorphism for static polymorphism. Without more details on the problem at hand, it is not possible to know whether that is a valid approach or not, as it basically breaks the polymorphic hierarchy: with CRTP there is no single base class, but rather a family of them. You cannot hold objects of Derived1 and Derived2 in the same container as they are unrelated... It is a fine solution if all you need is to share the code, but not if you need dynamic polymorphism. Take a look at the Visitor pattern and at double-dispatch for similar problems.

If you need dynamic polymorphism, you could try to implement double dispatch (it is a pain, but feasible if the hierarchy is small enough. Basically create two different hierarchies, one rooted at Base and another that serves as some short of manual dispatcher. The hierarchy rooted at Base will have a virtual method apply, and the second hierarchy will have virtual functions for each one of the types in the first hierarchy:

```<code>class Base;
class Derived1;  // inherits from Base, implements Visitor
class Derived2;  // inherits from either Base or Derived2
struct Visitor {
   virtual void visit( Base& ) = 0;     // manually unrolled for all types
   virtual void visit( Derived1& ) = 0;
   virtual void visit( Derived2& ) = 0;
};
struct Base {
   virtual void apply( Visitor& v ) {   // manually replicate this in Derived1, 2
      v.visit( *this );
   }
   template <typename T> void foo(T);   // implement
};

template <typename T>
struct FooCaller : Visitor {
    T& ref_value;
    FooCaller( T& v ) : ref_value(v) {}
    template <typename U> void call_foo( U& o ) {
       o.foo(ref_value);
    }
    virtual void visit( Base & b )      { call_foo(b); }
    virtual void visit( Derived1 & d1 ) { call_foo(d1); }
    virtual void visit( Derived2 & d2 ) { call_foo(d2); }
};
</code>```

The names I have used are common in the Visitor pattern, and this approach is quite similar to that pattern (I don't dare call it the Visitor pattern, but the approach is similar, so I just borrowed the naming convention).

User code would be similar to:

```<code>int main()                     // main returns int, not void!!!
{
   Base* BasePtr = new Derived1();
   int i = 5;
   FooCaller<int> c(i)
   BasePtr->apply(c);          // [1] magic happens here
}
</code>```

The requirement of declaring i and c before hand can be released by changing (if possible) the arguments to the functions from references to const-references. The actual magic is that in [1] the C++ single dispatch mechanism sill dispatch the call to Derived1::apply, since that is the dynamic type of the object pointed by BasePtr. At that point it will call Visitor::visit( Derived1& ) with itself as the argument. That will again be dispatched through the single dispatch mechanism to FooCaller<int>::visit( Derived1& ), and at that point both objects have been resolved to their static types. When FooCaller<int>::visit calls call_foo the argument U is deduced to be Derived1, when it calls Derived1::foo the argument is deduced to be int and it ends up calling Derived1::foo<int>... though a couple of loops and indirections...

Depending on your particular use case this might be too complex (if static polymorphism like CRTP would work) or too hard to maintain (if the hierarchy is big: for each new element in the Base hierarchy you will have to update all types in the hierarchy of the Visitor), so if you can avoid this complexity, perfect. In some cases, though, you need this.

Also note that this is the most complex fully dynamic solution, there are other options in between, depending on what is it that you need to be runtime polymorphism... It might be the case that your hierarchy models a visitor of shorts, and that you only need to manually unroll the different virtual functions that will dispatch to the template internally, in which case half of the above complexity will be gone.

Also note that this is quite unusual in C++, and that if you explain the actual problem at hand, there might be better simpler solutions, what you have stated are the requirements of your solution to the original problem: dynamically dispatch to a template.

Body:
I'm having a problem in C++ with calling a function of a derived class while having a pointer to the base class.

EDIT:
Some answers referred me to CRTP

but my point is that I need to have a pointer to the "Base*" class not "Base*" because I'm unaware of the type currently being handled (The current instance is created from some sort of a factory).

Classes:

class Base
{
..
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

Usage:

int main()
{
   Base* BasePtr = new Derived1();

   // The expected function to be called is Derived1::func<int>()
   BasePtr->func<int>();

   return 0; // :)
}

I can't make func virtual because the language does not support virtual template function.

It is only allowed if only the class is have template arguments but not if the function within it has template arguments.

I have seen a similar problem resolved within Boost.Serialization but couldn't understand the solution.

Thanks,

Koby Meir

Body:
The two existing solutions trade dynamic polymorphism for static polymorphism. Without more details on the problem at hand, it is not possible to know whether that is a valid approach or not, as it basically breaks the polymorphic hierarchy: with CRTP there is no single base class, but rather a family of them. You cannot hold objects of Derived1 and Derived2 in the same container as they are unrelated... It is a fine solution if all you need is to share the code, but not if you need dynamic polymorphism. Take a look at the Visitor pattern and at double-dispatch for similar problems.

If you need dynamic polymorphism, you could try to implement double dispatch (it is a pain, but feasible if the hierarchy is small enough. Basically create two different hierarchies, one rooted at Base and another that serves as some short of manual dispatcher. The hierarchy rooted at Base will have a virtual method apply, and the second hierarchy will have virtual functions for each one of the types in the first hierarchy:

class Base;
class Derived1;  // inherits from Base, implements Visitor
class Derived2;  // inherits from either Base or Derived2
struct Visitor {
   virtual void visit( Base& ) = 0;     // manually unrolled for all types
   virtual void visit( Derived1& ) = 0;
   virtual void visit( Derived2& ) = 0;
};
struct Base {
   virtual void apply( Visitor& v ) {   // manually replicate this in Derived1, 2
      v.visit( *this );
   }
   template <typename T> void foo(T);   // implement
};

template <typename T>
struct FooCaller : Visitor {
    T& ref_value;
    FooCaller( T& v ) : ref_value(v) {}
    template <typename U> void call_foo( U& o ) {
       o.foo(ref_value);
    }
    virtual void visit( Base & b )      { call_foo(b); }
    virtual void visit( Derived1 & d1 ) { call_foo(d1); }
    virtual void visit( Derived2 & d2 ) { call_foo(d2); }
};

The names I have used are common in the Visitor pattern, and this approach is quite similar to that pattern (I don't dare call it the Visitor pattern, but the approach is similar, so I just borrowed the naming convention).

User code would be similar to:

int main()                     // main returns int, not void!!!
{
   Base* BasePtr = new Derived1();
   int i = 5;
   FooCaller<int> c(i)
   BasePtr->apply(c);          // [1] magic happens here
}

The requirement of declaring i and c before hand can be released by changing (if possible) the arguments to the functions from references to const-references. The actual magic is that in [1] the C++ single dispatch mechanism sill dispatch the call to Derived1::apply, since that is the dynamic type of the object pointed by BasePtr. At that point it will call Visitor::visit( Derived1& ) with itself as the argument. That will again be dispatched through the single dispatch mechanism to FooCaller<int>::visit( Derived1& ), and at that point both objects have been resolved to their static types. When FooCaller<int>::visit calls call_foo the argument U is deduced to be Derived1, when it calls Derived1::foo the argument is deduced to be int and it ends up calling Derived1::foo<int>... though a couple of loops and indirections...

Depending on your particular use case this might be too complex (if static polymorphism like CRTP would work) or too hard to maintain (if the hierarchy is big: for each new element in the Base hierarchy you will have to update all types in the hierarchy of the Visitor), so if you can avoid this complexity, perfect. In some cases, though, you need this.

Also note that this is the most complex fully dynamic solution, there are other options in between, depending on what is it that you need to be runtime polymorphism... It might be the case that your hierarchy models a visitor of shorts, and that you only need to manually unroll the different virtual functions that will dispatch to the template internally, in which case half of the above complexity will be gone.

Also note that this is quite unusual in C++, and that if you explain the actual problem at hand, there might be better simpler solutions, what you have stated are the requirements of your solution to the original problem: dynamically dispatch to a template.


问:
Why IGNORECASE awk variable does not work properly when its value is set in the command line option?
I realized that awk -v IGNORECASE=0 is ignoring the case when it shouldn't.

```<code>ps -ef | awk -v IGNORECASE=0 '/INIT/'
root          1      0  0  2019 ?        00:03:07 /sbin/init
root      65327  25751  0 08:26 pts/0    00:00:00 awk -v IGNORECASE=0 /INIT/
</code>```

but awk 'BEGIN { IGNORECASE=0 }' is not ignoring the case as expected.

```<code>ps -ef | awk  'BEGIN { IGNORECASE=0 } /INIT/'
root      66290  25751  0 08:27 pts/0    00:00:00 awk BEGIN { IGNORECASE=0 } /INIT/
</code>```

Why? What am I missing? Is it a bug?

P.D: GNU Awk 3.1.7

答:
Found in the gawk changelog:

2015-02-05         Andrew J. Schorr

eval.c (set_IGNORECASE): If IGNORECASE has a numeric value, try
  using that before treating it as a string.  This fixes a problem
  where setting -v IGNORECASE=0 on the command line was not working
  properly.

Bug confirmed. You're not missing anything.

Hopefully you can upgrade to the latest version.

Body:
I realized that awk -v IGNORECASE=0 is ignoring the case when it shouldn't.

ps -ef | awk -v IGNORECASE=0 '/INIT/'
root          1      0  0  2019 ?        00:03:07 /sbin/init
root      65327  25751  0 08:26 pts/0    00:00:00 awk -v IGNORECASE=0 /INIT/

but awk 'BEGIN { IGNORECASE=0 }' is not ignoring the case as expected.

ps -ef | awk  'BEGIN { IGNORECASE=0 } /INIT/'
root      66290  25751  0 08:27 pts/0    00:00:00 awk BEGIN { IGNORECASE=0 } /INIT/

Why? What am I missing? Is it a bug?

P.D: GNU Awk 3.1.7


问:
Best strategy to backup mongodb docker instance?
In the mongodb docker page there's the following tutorial on how to dump a mongodb collection:

```<code>sudo docker exec container_name sh -c 'exec mongodump -d collection_name --archive' > /home/mongo_backup/all-collections.archive
</code>```

I thougth of creating another container which runs this dump periodically (twice a day for example) and saves to a folder that is mounted inside it. But can I mongodump from a container that is not the container that has the collections? Can I mongodump via local network?

After this is solved, there's still the problem of where to send this backup. It can't be on the same place as my code deployed because it can be erased accidentaly.

Is this a good backup strategy? Any better ideas?

答:
I thougth of creating another container which runs this dump periodically [...] there's still the problem of where to send this backup

mgob - "MongoDB dockerized backup agent" does just that: it's a container running mongodump periodically with features to upload generated dump to various Clouds, S3 and SFTP.

We've been using it for some time both with Docker and Kubernetes with good results.

Body:
In the mongodb docker page there's the following tutorial on how to dump a mongodb collection:

sudo docker exec container_name sh -c 'exec mongodump -d collection_name --archive' > /home/mongo_backup/all-collections.archive

I thougth of creating another container which runs this dump periodically (twice a day for example) and saves to a folder that is mounted inside it. But can I mongodump from a container that is not the container that has the collections? Can I mongodump via local network?

After this is solved, there's still the problem of where to send this backup. It can't be on the same place as my code deployed because it can be erased accidentaly.

Is this a good backup strategy? Any better ideas?


问:
Remove Specific Characters/Strings/Sequences of Characters in Python
I am creating a long list of what seem to be tuples that I would like to later convert into a Dataframe, but there are certain common sequences of characters that prevent this from being possible. And example of a fraction of the output:

```<code>0,"GAME_ID                      21900001
EVENTNUM                            2
EVENTMSGTYPE                       12
EVENTMSGACTIONTYPE                  0
PERIOD                              1
WCTIMESTRING                  8:04 PM
PCTIMESTRING                    12:00
HOMEDESCRIPTION
NEUTRALDESCRIPTION
VISITORDESCRIPTION
SCORE                             NaN
SCOREMARGIN                       NaN
PERSON1TYPE                         0
PLAYER1_ID                          0
PLAYER1_NAME                      NaN
PLAYER1_TEAM_ID                   NaN
PLAYER1_TEAM_CITY                 NaN
PLAYER1_TEAM_NICKNAME             NaN
PLAYER1_TEAM_ABBREVIATION         NaN
PERSON2TYPE                         0
PLAYER2_ID                          0
PLAYER2_NAME                      NaN
PLAYER2_TEAM_ID                   NaN
PLAYER2_TEAM_CITY                 NaN
PLAYER2_TEAM_NICKNAME             NaN
PLAYER2_TEAM_ABBREVIATION         NaN
PERSON3TYPE                         0
PLAYER3_ID                          0
PLAYER3_NAME                      NaN
PLAYER3_TEAM_ID                   NaN
PLAYER3_TEAM_CITY                 NaN
PLAYER3_TEAM_NICKNAME             NaN
PLAYER3_TEAM_ABBREVIATION         NaN
VIDEO_AVAILABLE_FLAG                0
DESCRIPTION
TIME_ELAPSED                        0
TIME_ELAPSED_PERIOD                 0
Name: 0, dtype: object"
</code>```

Whereas the desired output would be:

```<code>GAME_ID                      21900001
EVENTNUM                            2
EVENTMSGTYPE                       12
EVENTMSGACTIONTYPE                  0
PERIOD                              1
WCTIMESTRING                  8:04 PM
PCTIMESTRING                    12:00
HOMEDESCRIPTION
NEUTRALDESCRIPTION
VISITORDESCRIPTION
SCORE                             NaN
SCOREMARGIN                       NaN
PERSON1TYPE                         0
PLAYER1_ID                          0
PLAYER1_NAME                      NaN
PLAYER1_TEAM_ID                   NaN
PLAYER1_TEAM_CITY                 NaN
PLAYER1_TEAM_NICKNAME             NaN
PLAYER1_TEAM_ABBREVIATION         NaN
PERSON2TYPE                         0
PLAYER2_ID                          0
PLAYER2_NAME                      NaN
PLAYER2_TEAM_ID                   NaN
PLAYER2_TEAM_CITY                 NaN
PLAYER2_TEAM_NICKNAME             NaN
PLAYER2_TEAM_ABBREVIATION         NaN
PERSON3TYPE                         0
PLAYER3_ID                          0
PLAYER3_NAME                      NaN
PLAYER3_TEAM_ID                   NaN
PLAYER3_TEAM_CITY                 NaN
PLAYER3_TEAM_NICKNAME             NaN
PLAYER3_TEAM_ABBREVIATION         NaN
VIDEO_AVAILABLE_FLAG                0
DESCRIPTION
TIME_ELAPSED                        0
TIME_ELAPSED_PERIOD                 0
</code>```

How can I get rid of the 0 and " at the start, and then the trash at the end past the TIME_ELAPSED_PERIOD? The int at the start and the one in the bottom row increases by 1 until the end of my program, which could likely go upwards of around 320,000, so I will need the code to be able to adapt for a range of int values. I think it would be easiest to do this after the creation of my list, so it shouldn't be necessary for me to show you any of my code. Just a systematic manipulation of characters should do the trick. Thanks!

答:
Provided that your input data is in the form of a list, you can try the following to meet your requirements:</p>

```<code>inputlist = Your_list_to_be_corrected  #Assign your input list here

# Now, remove the rows in the list that have the format "Name: 0, dtype: object""
inputlist = [ x for x in inputlist if "dtype: object" not in x ]

#Now, correct the rows containing GAME_ID by removing the int number and special characters
sep = 'GAME_ID'
for index, element in enumerate(inputlist):
    if "GAME_ID" in element:
        inputlist[index] = 'GAME_ID' + element.split(sep, 1)[1]
</code>```

Body:
I am creating a long list of what seem to be tuples that I would like to later convert into a Dataframe, but there are certain common sequences of characters that prevent this from being possible. And example of a fraction of the output:

0,"GAME_ID                      21900001
EVENTNUM                            2
EVENTMSGTYPE                       12
EVENTMSGACTIONTYPE                  0
PERIOD                              1
WCTIMESTRING                  8:04 PM
PCTIMESTRING                    12:00
HOMEDESCRIPTION
NEUTRALDESCRIPTION
VISITORDESCRIPTION
SCORE                             NaN
SCOREMARGIN                       NaN
PERSON1TYPE                         0
PLAYER1_ID                          0
PLAYER1_NAME                      NaN
PLAYER1_TEAM_ID                   NaN
PLAYER1_TEAM_CITY                 NaN
PLAYER1_TEAM_NICKNAME             NaN
PLAYER1_TEAM_ABBREVIATION         NaN
PERSON2TYPE                         0
PLAYER2_ID                          0
PLAYER2_NAME                      NaN
PLAYER2_TEAM_ID                   NaN
PLAYER2_TEAM_CITY                 NaN
PLAYER2_TEAM_NICKNAME             NaN
PLAYER2_TEAM_ABBREVIATION         NaN
PERSON3TYPE                         0
PLAYER3_ID                          0
PLAYER3_NAME                      NaN
PLAYER3_TEAM_ID                   NaN
PLAYER3_TEAM_CITY                 NaN
PLAYER3_TEAM_NICKNAME             NaN
PLAYER3_TEAM_ABBREVIATION         NaN
VIDEO_AVAILABLE_FLAG                0
DESCRIPTION
TIME_ELAPSED                        0
TIME_ELAPSED_PERIOD                 0
Name: 0, dtype: object"

Whereas the desired output would be:

GAME_ID                      21900001
EVENTNUM                            2
EVENTMSGTYPE                       12
EVENTMSGACTIONTYPE                  0
PERIOD                              1
WCTIMESTRING                  8:04 PM
PCTIMESTRING                    12:00
HOMEDESCRIPTION
NEUTRALDESCRIPTION
VISITORDESCRIPTION
SCORE                             NaN
SCOREMARGIN                       NaN
PERSON1TYPE                         0
PLAYER1_ID                          0
PLAYER1_NAME                      NaN
PLAYER1_TEAM_ID                   NaN
PLAYER1_TEAM_CITY                 NaN
PLAYER1_TEAM_NICKNAME             NaN
PLAYER1_TEAM_ABBREVIATION         NaN
PERSON2TYPE                         0
PLAYER2_ID                          0
PLAYER2_NAME                      NaN
PLAYER2_TEAM_ID                   NaN
PLAYER2_TEAM_CITY                 NaN
PLAYER2_TEAM_NICKNAME             NaN
PLAYER2_TEAM_ABBREVIATION         NaN
PERSON3TYPE                         0
PLAYER3_ID                          0
PLAYER3_NAME                      NaN
PLAYER3_TEAM_ID                   NaN
PLAYER3_TEAM_CITY                 NaN
PLAYER3_TEAM_NICKNAME             NaN
PLAYER3_TEAM_ABBREVIATION         NaN
VIDEO_AVAILABLE_FLAG                0
DESCRIPTION
TIME_ELAPSED                        0
TIME_ELAPSED_PERIOD                 0

How can I get rid of the 0 and " at the start, and then the trash at the end past the TIME_ELAPSED_PERIOD? The int at the start and the one in the bottom row increases by 1 until the end of my program, which could likely go upwards of around 320,000, so I will need the code to be able to adapt for a range of int values. I think it would be easiest to do this after the creation of my list, so it shouldn't be necessary for me to show you any of my code. Just a systematic manipulation of characters should do the trick. Thanks!

Body:
Provided that your input data is in the form of a list, you can try the following to meet your requirements:

inputlist = Your_list_to_be_corrected  #Assign your input list here

# Now, remove the rows in the list that have the format "Name: 0, dtype: object""
inputlist = [ x for x in inputlist if "dtype: object" not in x ]

#Now, correct the rows containing GAME_ID by removing the int number and special characters
sep = 'GAME_ID'
for index, element in enumerate(inputlist):
    if "GAME_ID" in element:
        inputlist[index] = 'GAME_ID' + element.split(sep, 1)[1]


问:
Why does Stream.reduce take BinaryOperator<T> rather than BiFunction<T, T, T>?
For my specific case I want to use functional composition in a reduction; for example:

```<code>BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());
</code>```

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator
```

<p>Instead, I need to do:</p>

```ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());
```

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

答:
This may be to clearly state the intent that the reduction should not be cumulative (see Reduction operations), and must be an operation not a function (too general).
As an operation is usually thought as operating by value?

Naman's answer is also a good hint on that as reduce(biFunction::apply) can be very easily applied for.

Body:
For my specific case I want to use functional composition in a reduction; for example:

BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator

Instead, I need to do:

ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?


问:
Continuous animation problem even if hovered out
I have a button that will fade a div upon hover.
If I hover in a button then hover out and repeat that procedure multiple times in quick succession then hover out, the div will go on animating when it should have stopped.
Please refer to the following snippet.

http://jsfiddle.net/arvinboggs/uenEQ/9/

Is there a way to correct this behavior?

Is there a way stop the animation on the final hover out?

答: Yep. You need to .stop() before you .animate() again: http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup. Otherwise you build up an animation queue that has to dequeue.


问:
How do I escape double quote and other troublesome characters in Powershell regex
I've hit a snag in a script I'm putting together to download the latest installation packages without needing to use Chocolatey or Ketarin. Unfortunately a few utilities aren't provided at a direct download link and are hidden behind redirecting URLs, with the download URL expiring after 15 minutes. To complicate things a bit further, I'm doing this in PowerShell 2 as we have a few Vista machines in our office.

After researching other similar scenarios, it seems as though I can invoke the .NET WebClient to handle the download, though there isn't a progress bar. As I haven't found a sample of code to handle downloading files behind redirects after a certain amount of time that works with a .NET WebClient, I decided that what I could do is use a WebClient request to load the page, and then get the current direct download URL from the page using the following regex, and then use a regex to that URL to download the file. I've checked with regexr.com to verify that the regex catches the sample URL below.

Sample URL

```<code><a href="https://www.example.com/randomstring003ejdjd38/dl/ProgramName.exe">CF DL here</a>
</code>```

Regex

```<code><a(?: [^>]*?)? href=(["'])([^\1]*?ProgramName*?)\1(?: .*?)?>.*?<\/a>
</code>```

Unfortunately Powershell red flags this, as it seems to think the double quotes need to be terminated. After attempting to escape any red-flagged characters using backticks, I've wound up with the following, that throws a error saying that '?:' is not recognized as a term, cmdlet, etc.

```<code>$downloadLinkRegex = New-Object System.Text.RegularExpressions.Regex (<a(?: [^>]*?)? href=(`[`"`'])(`[`^\1]*?ProgramName.exe*?)\1(?: .*?)?>.*?</a>)
if ("https://www.example.com/randomstring003ejdjd38/dl/ProgramName.exe" -match $downloadLinkRegex){
write-host "yay"
} else{
write-host "nope"}
</code>```

Attempts to escape the ? using backticks fails also. Regex's are incredibly difficult for me, so at this point I'm out of ideas on how to make the ISE recognize that this is a valid regex, and that it doesn't need to be validated, and that it can be stored as the value of a variable to be called later on the contents of a webrequest.

If anyone could point out where I've gone wrong, or how to resolve the issue, I would be immensely grateful.

答:
Looks good</p>

```<code>$a='<a href="https://www.example.com/randomstring003ejdjd38/dl/ProgramName.exe">CF DL here</a>'
$a -match '(?<=ef=")[^"]+?(\w+).(exe|pdf)'
Iwr $matches[0] -outfile "$($matches[1]).$($matches[2])"
</code>```

Body:
I've hit a snag in a script I'm putting together to download the latest installation packages without needing to use Chocolatey or Ketarin. Unfortunately a few utilities aren't provided at a direct download link and are hidden behind redirecting URLs, with the download URL expiring after 15 minutes. To complicate things a bit further, I'm doing this in PowerShell 2 as we have a few Vista machines in our office.

After researching other similar scenarios, it seems as though I can invoke the .NET WebClient to handle the download, though there isn't a progress bar. As I haven't found a sample of code to handle downloading files behind redirects after a certain amount of time that works with a .NET WebClient, I decided that what I could do is use a WebClient request to load the page, and then get the current direct download URL from the page using the following regex, and then use a regex to that URL to download the file. I've checked with regexr.com to verify that the regex catches the sample URL below.

Sample URL

CF DL here

Regex

]*?)? href=(["'])([^\1]*?ProgramName*?)\1(?: .*?)?>.*?<\/a>

Unfortunately Powershell red flags this, as it seems to think the double quotes need to be terminated. After attempting to escape any red-flagged characters using backticks, I've wound up with the following, that throws a error saying that '?:' is not recognized as a term, cmdlet, etc.

$downloadLinkRegex = New-Object System.Text.RegularExpressions.Regex (]*?)? href=(`[`"`'])(`[`^\1]*?ProgramName.exe*?)\1(?: .*?)?>.*?)
if ("https://www.example.com/randomstring003ejdjd38/dl/ProgramName.exe" -match $downloadLinkRegex){
write-host "yay"
} else{
write-host "nope"}

Attempts to escape the ? using backticks fails also. Regex's are incredibly difficult for me, so at this point I'm out of ideas on how to make the ISE recognize that this is a valid regex, and that it doesn't need to be validated, and that it can be stored as the value of a variable to be called later on the contents of a webrequest.

If anyone could point out where I've gone wrong, or how to resolve the issue, I would be immensely grateful.

Body:
Looks good

$a='<a href="https://www.example.com/randomstring003ejdjd38/dl/ProgramName.exe">CF DL here</a>'
$a -match '(?<=ef=")[^"]+?(\w+).(exe|pdf)'
Iwr $matches[0] -outfile "$($matches[1]).$($matches[2])"


问:
Linking Fragments With Buttons
Can someone please help me?
i just want to add 2 Buttons in a activity and each button goes to a different fragment
for example:
Button 1 goes to Login_Fragment

Button 2 goes to SignUp_Fragment
those fragments have their own xml files
the code below is FirstPage and it's xml is first_page
so the below code will replace the first_page xml with the fragments xml files
how can i prevent that?

```<code>package com.example.logindesign;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

public class First_Page extends AppCompatActivity {
    Button createAccount, login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_page);

        createAccount = findViewById(R.id.createAccount);
        createAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                SignUp_Fragment f2 = new SignUp_Fragment();
                fm.beginTransaction().replace(R.id.mParent, f2).commit();
            }
        });

        login = findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                Login_Fragment f2 = new Login_Fragment();
                fm.beginTransaction().add(R.id.mParent, f2).commit();
            }
        });
    }
}
</code>```

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/Blue"
    android:id="@+id/mParent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/stay_connected_with_friends"
        android:textSize="28sp"
        android:textColor="@color/white"
        android:fontFamily="@font/nunito_bold"
        android:layout_marginTop="230dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="200dp"
        >

    </TextView>

    <Button
        android:id="@+id/createAccount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/sign_up"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="200dp"
        android:layout_marginBottom="172dp"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/login"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="175dp"
        android:layout_height="141dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="114dp"
        android:layout_marginBottom="136dp"
        android:contentDescription="@string/logo"
        app:srcCompat="@drawable/logo" />

</RelativeLayout>
</code>```

答:
I use FragmentManager

https://developer.android.com/reference/androidx/fragment/app/FragmentManager?hl=en
and use tags to determine how the navigation flows

```<code>class MainMenuFragment : Fragment() {
    private lateinit var supportFragmentManager: FragmentManager
</code>```

```<code>    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewFragment = inflater.inflate(R.layout.main_menu_fragment, container, false)
        supportFragmentManager = activity!!.supportFragmentManager

        val buttonDocumentList: Button = viewFragment.findViewById(R.id.btn_menu_top_left)
        buttonDocumentList.setOnClickListener {
            replaceFragment(
                DocumentListFragment.newInstance(), "${FragmentTypes.DOCUMENT_LIST}"
            )
        }
</code>```

```<code>    private fun replaceFragment(fragment: Fragment, tag: String) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.main_activity_container, fragment, tag)
            .commitNow()
    }
</code>```

Title: Linking Fragments With Buttons

Body:
Can someone please help me?
i just want to add 2 Buttons in a activity and each button goes to a different fragment
for example:
Button 1 goes to Login_Fragment

Button 2 goes to SignUp_Fragment
those fragments have their own xml files
the code below is FirstPage and it's xml is first_page
so the below code will replace the first_page xml with the fragments xml files
how can i prevent that?

package com.example.logindesign;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

public class First_Page extends AppCompatActivity {
    Button createAccount, login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_page);

        createAccount = findViewById(R.id.createAccount);
        createAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                SignUp_Fragment f2 = new SignUp_Fragment();
                fm.beginTransaction().replace(R.id.mParent, f2).commit();
            }
        });

        login = findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                Login_Fragment f2 = new Login_Fragment();
                fm.beginTransaction().add(R.id.mParent, f2).commit();
            }
        });
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/Blue"
    android:id="@+id/mParent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/stay_connected_with_friends"
        android:textSize="28sp"
        android:textColor="@color/white"
        android:fontFamily="@font/nunito_bold"
        android:layout_marginTop="230dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="200dp"
        >

    </TextView>

    <Button
        android:id="@+id/createAccount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/sign_up"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="200dp"
        android:layout_marginBottom="172dp"
        android:background="@color/Blue"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/login"
        android:textColor="@color/white"
        android:textSize="25sp">

    </Button>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="175dp"
        android:layout_height="141dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="114dp"
        android:layout_marginBottom="136dp"
        android:contentDescription="@string/logo"
        app:srcCompat="@drawable/logo" />

</RelativeLayout>

Body:
I use FragmentManager

https://developer.android.com/reference/androidx/fragment/app/FragmentManager?hl=en
and use tags to determine how the navigation flows

class MainMenuFragment : Fragment() {
    private lateinit var supportFragmentManager: FragmentManager

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewFragment = inflater.inflate(R.layout.main_menu_fragment, container, false)
        supportFragmentManager = activity!!.supportFragmentManager

        val buttonDocumentList: Button = viewFragment.findViewById(R.id.btn_menu_top_left)
        buttonDocumentList.setOnClickListener {
            replaceFragment(
                DocumentListFragment.newInstance(), "${FragmentTypes.DOCUMENT_LIST}"
            )
        }

    private fun replaceFragment(fragment: Fragment, tag: String) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.main_activity_container, fragment, tag)
            .commitNow()
    }


问:
Terraform azurerm_virtual_machine_extension, run local PowerShell Script using CustomScriptExtension
How to run a local ( without storing to a blob storage account ) PowerShell script in terraform  azurerm_virtual_machine_extension

Folder having

main.tf

install.ps1

resource "azurerm_virtual_machine_extension" "software" {
      name                 = "install-software"
      resource_group_name  = azurerm_resource_group.azrg.name
      virtual_machine_id   = azurerm_virtual_machine.vm.id
      publisher            = "Microsoft.Compute"
      type                 = "CustomScriptExtension"
      type_handler_version = "1.9"

```<code>  settings = <<SETTINGS
    {
      "commandToExecute": "powershell -ExecutionPolicy Unrestricted -File \"install.ps1\""
    }
    SETTINGS
}
</code>```

but failed

```<code>[
        {
            "code": "ComponentStatus/StdOut/succeeded",
            "level": "Info",
            "displayStatus": "Provisioning succeeded",
            "message": "Windows PowerShell \r\nCopyright (C) Microsoft Corporation. All rights reserved.\r\n\r\n"
        },
        {
            "code": "ComponentStatus/StdErr/succeeded",
            "level": "Info",
            "displayStatus": "Provisioning succeeded",
            "message": "The argument 'install.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.\r\n"
        }
    ]
</code>```

any lead.

Thanks

答:
this worked for me.</p>

```<code>resource "azurerm_virtual_machine_extension" "software" {
  name                 = "install-software"
  resource_group_name  = azurerm_resource_group.azrg.name
  virtual_machine_id   = azurerm_virtual_machine.vm.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  protected_settings = <<SETTINGS
  {
    "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.tf.rendered)}')) | Out-File -filepath install.ps1\" && powershell -ExecutionPolicy Unrestricted -File install.ps1"
  }
  SETTINGS
}

data "template_file" "tf" {
    template = "${file("install.ps1")}"
}
</code>```

Body:
How to run a local ( without storing to a blob storage account ) PowerShell script in terraform  azurerm_virtual_machine_extension

Folder having

main.tf

install.ps1

resource "azurerm_virtual_machine_extension" "software" {
      name                 = "install-software"
      resource_group_name  = azurerm_resource_group.azrg.name
      virtual_machine_id   = azurerm_virtual_machine.vm.id
      publisher            = "Microsoft.Compute"
      type                 = "CustomScriptExtension"
      type_handler_version = "1.9"

  settings = <<SETTINGS
    {
      "commandToExecute": "powershell -ExecutionPolicy Unrestricted -File \"install.ps1\""
    }
    SETTINGS
}

but failed

[
        {
            "code": "ComponentStatus/StdOut/succeeded",
            "level": "Info",
            "displayStatus": "Provisioning succeeded",
            "message": "Windows PowerShell \r\nCopyright (C) Microsoft Corporation. All rights reserved.\r\n\r\n"
        },
        {
            "code": "ComponentStatus/StdErr/succeeded",
            "level": "Info",
            "displayStatus": "Provisioning succeeded",
            "message": "The argument 'install.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.\r\n"
        }
    ]

any lead.

Thanks

Body:
this worked for me.

resource "azurerm_virtual_machine_extension" "software" {
  name                 = "install-software"
  resource_group_name  = azurerm_resource_group.azrg.name
  virtual_machine_id   = azurerm_virtual_machine.vm.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  protected_settings = <<SETTINGS
  {
    "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.tf.rendered)}')) | Out-File -filepath install.ps1\" && powershell -ExecutionPolicy Unrestricted -File install.ps1"
  }
  SETTINGS
}

data "template_file" "tf" {
    template = "${file("install.ps1")}"
}


问:
Setting a greeting based on user's time (Good morning, good afternoon…)
Can anyone extrapolate on how to implement a basic "good evening" or "good morning" based on the user's time setting?

Perhaps PHP will fetch the server time, but I'm looking to greet the site visitor with a time-based appropriate greeting that considers their time of day.

E.G.: good morning, good night, good afternoon.

答:
```<code>function greeting_msg() {
    $hour = date('H');
    if ($hour >= 18) {
       $greeting = "Good Evening";
    } elseif ($hour >= 12) {
        $greeting = "Good Afternoon";
    } elseif ($hour < 12) {
       $greeting = "Good Morning";
    }
    return $greeting;
}
</code>```


问:
How often false signals are triggered in a condition variable?
I don’t understand why std::condition_variable has more standard guarantees than this code:</p>

```<code>class condition_variable {
public:
  void notify_one() {}
  void notify_all() {}
  void wait(unique_lock<mutex> &lock) {
    lock.unlock();
    this_thread::sleep_for(15ms);
    lock.lock();
  }
  void wait(unique_lock<mutex> &lock,
            const function<bool()> &pred) {
    while (!pred()) wait(lock);
  }
};
</code>```

答:
The condition variable is intended to use a semaphore, which allows waiting without using CPU cycles. Your implementation locks and unlocks mutex repeatedly, and without the sleep it would consume 100% of the CPU.

With the sleep there is a fixed delay when waking up, which is also a disadvantage compared to a semaphore. The operating system knows who are waiting for each condition variable, and therefore it is efficient to wake up.

On Windows, std::condition_variable would use SleepConditionVariableCS to wait, and generally utilize the operating system condition variable API.

Body:
I don’t understand why std::condition_variable has more standard guarantees than this code:

class condition_variable {
public:
  void notify_one() {}
  void notify_all() {}
  void wait(unique_lock<mutex> &lock) {
    lock.unlock();
    this_thread::sleep_for(15ms);
    lock.lock();
  }
  void wait(unique_lock<mutex> &lock,
            const function<bool()> &pred) {
    while (!pred()) wait(lock);
  }
};