答:
You have to add the "new int[] {1,2,3,4}"

This will complile (just tested):

```<code>class Program
{
    static void Main(string[] args)
    {
        TwoSums(new [] { 2, 7, 11, 15}, 9); //No error here anymore  :)
    }

    public static int[] TwoSums(int[] nums, int target)
    {
        for (int i = 0; i < nums.Length; i++)
        {
            for (int j = i + 1; i < nums.Length; j++)
            {
                if (nums[i] + nums[j] == target)
                    return new int[]
                     {
                    i,j
                     };
            }
        }
        return Array.Empty<int>();
    }
}
</code>```

Title: Why wont my Void Main run my public static int[] C#

Body:
You have to add the "new int[] {1,2,3,4}"

This will complile (just tested):

class Program
{
    static void Main(string[] args)
    {
        TwoSums(new [] { 2, 7, 11, 15}, 9); //No error here anymore  :)
    }

    public static int[] TwoSums(int[] nums, int target)
    {
        for (int i = 0; i < nums.Length; i++)
        {
            for (int j = i + 1; i < nums.Length; j++)
            {
                if (nums[i] + nums[j] == target)
                    return new int[]
                     {
                    i,j
                     };
            }
        }
        return Array.Empty<int>();
    }
}


来源: stackexchange

问:
NodeJS Wifi Network Trilateration using Lat, Lon & RSSI
I am trying to build an algorithm for locating a WiFi networks approximate location (Lat/Lon) using latitude, longitude and RSSI.

I built a NodeJS wifi scanner that constantly scans for wifi networks. Each network is tracked by mac address and has a tracking array that contains RSSI, Lat coordinate and Lon coordinate that is captured each time the scanner encounters a network.

Using this information, I want to calculate an approximate Lat/Lon coordinate/location for a particular network using the information contained in the tracking array for each access point.

Is there an existing implementation/algorithm for doing this?

```<code>"mac": "so:me:ra:nd:om:ac",
"ssid": "elcasa",
"channel": 5,
"tracking": [
  {
    "rssi": -79, // RSSI of signal when encountered by scanner
    "lat": "some-lat-coord", // Latitude of network when encountered by scanner using GPS
    "lon": "some-lon-coord"  // Longitude of network when encountered by scanner using GPS
  },
  {
    "rssi": -80,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -76,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -78,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -75,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -77,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -74,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  }
]
</code>```

答:
An rssi value does not provide enough info to give you a lat and lon.

For large scale cases like cell towers, you need at least two different listening posts to determine a lat and lon and a third if you want to know a depth coordinate.

In most settings where 2.4Ghz and 5Ghz are used, there is a lot of interference and you would need a considerable number of listening posts to determine an approximate coordinate.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build an algorithm for locating a WiFi networks approximate location (Lat/Lon) using latitude, longitude and RSSI.

I built a NodeJS wifi scanner that constantly scans for wifi networks. Each network is tracked by mac address and has a tracking array that contains RSSI, Lat coordinate and Lon coordinate that is captured each time the scanner encounters a network.

Using this information, I want to calculate an approximate Lat/Lon coordinate/location for a particular network using the information contained in the tracking array for each access point.

Is there an existing implementation/algorithm for doing this?

"mac": "so:me:ra:nd:om:ac",
"ssid": "elcasa",
"channel": 5,
"tracking": [
  {
    "rssi": -79, // RSSI of signal when encountered by scanner
    "lat": "some-lat-coord", // Latitude of network when encountered by scanner using GPS
    "lon": "some-lon-coord"  // Longitude of network when encountered by scanner using GPS
  },
  {
    "rssi": -80,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -76,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -78,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -75,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -77,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  },
  {
    "rssi": -74,
    "lat": "some-lat-coord",
    "lon": "some-lon-coord"
  }
]


问:
Nonblocking redirection of output from multiprocess process
I asked a question yesterday about a problem with a program I'm writing in Python ( Passing wxPython objects as multiprocessor arguments ). I managed to solve that problem by using a multiprocess process for the function that evaluates the scripts. However, since the scripts are runned from a different process, their output is not properly redirected to my wxPython TextCtrl window. So, I'm looking for way to continously redirect the output from the childprocess to my main process so it can be written to my text window.

This is the function that sets up the process:

```<code>def createprocess(test):
    q = Queue()
    q.put(test)
    p = Process(target=runtest, args=(q,))
    p.start()
    p.join()
    return q.get()
</code>```

This is the target function of the process:

```<code>def runtest(q):
    test = q.get()
    exec 'import ' + test
    func=test+'.'+test+'()'
    ret = eval(func)
    q.put(ret)
</code>```

I found this thread ( How can I send python multiprocessing Process output to a Tkinter gui ) which describes how to redirect output from the childprocess but the problem was that the output was received after the evaluation was complete.

答:
The solution to your immediate problem is to use two Queue.Queues instead of just one. Let's call them inqueue and outqueue. Then

```<code>def runtest(inqueue,outqueue):
    test = inqueue.get()
    module=__import__(test)
    ret=getattr(module,test)()
    outqueue.put(ret)
</code>```

The larger issue concerns how to control GUI elements like the TextCtrl with the output from a separate process. The answer is you don't. Instead spawn a thread (which can if you like spawn other processes), which can receive the values from outqueue and (unlike separate processes) update the TextCtrl.
See the LongRunningTasks wiki for examples on how to set this up.

ContentLicense: CC BY-SA 3.0

Body:
I asked a question yesterday about a problem with a program I'm writing in Python ( Passing wxPython objects as multiprocessor arguments ). I managed to solve that problem by using a multiprocess process for the function that evaluates the scripts. However, since the scripts are runned from a different process, their output is not properly redirected to my wxPython TextCtrl window. So, I'm looking for way to continously redirect the output from the childprocess to my main process so it can be written to my text window.

This is the function that sets up the process:

def createprocess(test):
    q = Queue()
    q.put(test)
    p = Process(target=runtest, args=(q,))
    p.start()
    p.join()
    return q.get()

This is the target function of the process:

def runtest(q):
    test = q.get()
    exec 'import ' + test
    func=test+'.'+test+'()'
    ret = eval(func)
    q.put(ret)

I found this thread ( How can I send python multiprocessing Process output to a Tkinter gui ) which describes how to redirect output from the childprocess but the problem was that the output was received after the evaluation was complete.

Body:
The solution to your immediate problem is to use two Queue.Queues instead of just one. Let's call them inqueue and outqueue. Then

def runtest(inqueue,outqueue):
    test = inqueue.get()
    module=__import__(test)
    ret=getattr(module,test)()
    outqueue.put(ret)

The larger issue concerns how to control GUI elements like the TextCtrl with the output from a separate process. The answer is you don't. Instead spawn a thread (which can if you like spawn other processes), which can receive the values from outqueue and (unlike separate processes) update the TextCtrl.
See the LongRunningTasks wiki for examples on how to set this up.


问:
Why wont my Void Main run my public static int[] C#
I'm having a hard time understanding why my method will not execute in my void Main. I have an array for the parameter but it will not execute.

```<code>   class Program
    {
        static void Main(string[] args)
        {
            TwoSums([2, 7, 11, 15],9); //Error is here.
        }

        public static int [] TwoSums(int[] nums, int target)
        {
            for(int i = 0; i <nums.Length; i++)
            {
                for(int j = i+1; i< nums.Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    return new int[]
                     {
                        i,j
                     };
                }
            }
            return Array.Empty<int>();
        }
    }
</code>```

答:
Some errors in your codes, so I provide a tested version:</p>
```<code>using System;

public class Program
{
    public static void Main(string[] args)
    {
        int[] x;
        int[] nums = new int[]{2, 7, 11, 15};

        x = TwoSums(nums, 9);

        foreach (int i in x)
        {
            System.Console.Write("{0} ", i);
        }
    }

    public static int[] TwoSums(int[] nums, int target)
    {
        for (int i = 0; i < nums.Length; i++)
        {
            for (int j = i + 1; i < nums.Length; j++)
            {
                if (nums[i] + nums[j] == target)
                    return new int[]{i, j};
            }
        }

        return Array.Empty<int>();
    }
}
</code>```

Body:
I'm having a hard time understanding why my method will not execute in my void Main. I have an array for the parameter but it will not execute.

   class Program
    {
        static void Main(string[] args)
        {
            TwoSums([2, 7, 11, 15],9); //Error is here.
        }

        public static int [] TwoSums(int[] nums, int target)
        {
            for(int i = 0; i <nums.Length; i++)
            {
                for(int j = i+1; i< nums.Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    return new int[]
                     {
                        i,j
                     };
                }
            }
            return Array.Empty<int>();
        }
    }

Body:
Some errors in your codes, so I provide a tested version:

using System;

public class Program
{
    public static void Main(string[] args)
    {
        int[] x;
        int[] nums = new int[]{2, 7, 11, 15};

        x = TwoSums(nums, 9);

        foreach (int i in x)
        {
            System.Console.Write("{0} ", i);
        }
    }

    public static int[] TwoSums(int[] nums, int target)
    {
        for (int i = 0; i < nums.Length; i++)
        {
            for (int j = i + 1; i < nums.Length; j++)
            {
                if (nums[i] + nums[j] == target)
                    return new int[]{i, j};
            }
        }

        return Array.Empty<int>();
    }
}


问:
Is there a way for a UWP app to know if Recurring Billing is turned on for a subscription in the Microsoft store
I have a Xamarin Forms UWP app.  I am trying to provide more specific information to users of my app regarding their subscription expiration / renewal.  I would like to be able to tell if they have turned off recurring billing for the subscription.  Below are the details I get back from the store regarding the current subscription.  I assume the isActive will turn to false after they turn off recurring billing AND cancel the subscription after Expiration date.  However, in my testing I have found that if they turn off recurring billing and are still within the the subscription period of their last recurring purchase (i.e. the expiration date is still in the future), everything seems to look exactly as if they have recurring billing turned on and the subscription will auto-renew.  I am trying find a way to let them know that their current subscription will expire on a specific date versus will auto-renew on a specific date.  Am I missing something?

Here is the code -- Everything works fine I just don't see anything in the object returned from the Microsoft Store API that indicates if recurring billing is on for the subscription.

```<code>using FCISharedAll;
using FCISuite.UWP;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.Services.Store;
using static FCISharedAll.FCIEnums.FlexEnums;

[assembly: Xamarin.Forms.Dependency(typeof(UWPSubscriptionManager))]
namespace FCISuite.UWP
{

public class UWPSubscriptionManager : IFCISubcriptionManager, IDisposable
{
    private StoreContext context = null;
    private static string[] ia_productKinds = { "Durable", "Consumable", "UnmanagedConsumable" };
    private List<String> iobj_filterList = null;

    //We need a constructor to load the list
    public UWPSubscriptionManager()
    {
        iobj_filterList = new List<string>(ia_productKinds);
    }

    /// <summary>
    /// This will run at the start of the app to get the active subscription info for the user.
    /// </summary>
    /// <returns></returns>
    public async Task<ActiveSubscriptionDetails> GetActiveSubscriptionInformation(ActiveSubscriptionDetails pobj_SubscriptionData)
    {
        string ls_Result = string.Empty;
        try
        {
            if (context == null)
            {
                context = StoreContext.GetDefault();
                // If your app is a desktop app that uses the Desktop Bridge, you
                // may need additional code to configure the StoreContext object.
                // For more info, see https://aka.ms/storecontext-for-desktop.
            }

            StoreAppLicense appLicense = await context.GetAppLicenseAsync();

            // Check if the customer has the rights to the subscription.
            foreach (var addOnLicense in appLicense.AddOnLicenses)
            {
                StoreLicense license = addOnLicense.Value;
                if (license.IsActive)
                {
                    pobj_SubscriptionData.ActiveSubscriptionID = license.SkuStoreId;
                    pobj_SubscriptionData.SubscriptionEndDate = license.ExpirationDate.DateTime;
                }
            }
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }
        //Debug.WriteLine("End of Subscription Info");

        return pobj_SubscriptionData;
    }

    #region get available subscriptions
    public async Task<List<SubscriptionDetail>> GetAvailableSubscriptions(string ps_ProductNotFoundMessage,
        string ps_StoreAddOnsNotFound, string ps_EnvironmentPrefix)
    {
        string ls_Result = "";
        List<SubscriptionDetail> lobj_AvailableSubscriptions = new List<SubscriptionDetail>();

        try
        {
            if (context == null)
            {
                context = StoreContext.GetDefault();
                // If your app is a desktop app that uses the Desktop Bridge, you
                // may need additional code to configure the StoreContext object.
                // For more info, see https://aka.ms/storecontext-for-desktop.
            }

            // Get app store product details. Because this might take several moments,
            // display a ProgressRing during the operation.
            StoreProductResult product_queryResult = await context.GetStoreProductForCurrentAppAsync();

            if (product_queryResult.Product == null)
            {
                // Show additional error info if it is available.
                if (product_queryResult.ExtendedError != null)
                {
                    ls_Result += $"\nExtendedError: {product_queryResult.ExtendedError.Message}";
                }

                // The Store catalog returned an unexpected result.
                throw new Exception(ps_ProductNotFoundMessage + " " + ls_Result);
            }
            else
            {
                StoreProductQueryResult addon_queryResult = await context.GetAssociatedStoreProductsAsync(iobj_filterList);

                if (addon_queryResult.ExtendedError != null)
                {
                    // The user may be offline or there might be some other server failure.
                    ls_Result = $"ExtendedError: {addon_queryResult.ExtendedError.Message}";

                    // The Store catalog returned an unexpected result for the Add-ons.
                    throw new Exception(ps_StoreAddOnsNotFound + " " + ls_Result);
                }
                List<KeyValuePair<string, StoreProduct>> lobj_ProductsforEnvironment = new List<KeyValuePair<string, StoreProduct>>();

                //We are in test - do not show the production subscriptions
                lobj_ProductsforEnvironment = (from tobj_Product in addon_queryResult.Products
                                               where tobj_Product.Value.Title.ToUpper().StartsWith(ps_EnvironmentPrefix.ToUpper())
                                               select tobj_Product).ToList();

                //foreach (KeyValuePair<string, StoreProduct> item in addon_queryResult.Products)
                foreach (KeyValuePair<string, StoreProduct> item in lobj_ProductsforEnvironment)
                {
                    // Add the store product's skus to the list
                    foreach (StoreSku lobj_Sku in item.Value.Skus)
                    {
                        if (lobj_Sku.IsSubscription)
                        {
                            lobj_AvailableSubscriptions.Add(new SubscriptionDetail()
                            {
                                SubscriptionID = item.Value.StoreId,
                                SubscriptionName = lobj_Sku.Title,
                                SubscriptionFormattedPrice = lobj_Sku.Price.FormattedPrice,
                                // Use the sku.SubscriptionInfo property to get info about the subscription.
                                // For example, the following code gets the units and duration of the
                                // subscription billing period.
                                SubscriptionPeriodUnit = lobj_Sku.SubscriptionInfo.BillingPeriodUnit.ToString(),
                                SubscriptionPeriod = lobj_Sku.SubscriptionInfo.BillingPeriod,
                            });
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }
        return lobj_AvailableSubscriptions;
    }
    #endregion

    #region Subscription Purchase area
    /// <summary>
    /// This will get the product for the ID from the store, then request to purchase it for the user.
    /// </summary>
    /// <param name="ps_SubscriptionStoreId">The ID of the store subscription to be purchased</param>
    /// <returns>boolean that indicates if the purchase succeeded or failed.</returns>
    public async Task<SubscriptionPurchaseDetail> PurchaseSubscription(string ps_SubscriptionStoreId)
    {
        SubscriptionPurchaseDetail lobj_SubscriptionPurchaseDetail = new SubscriptionPurchaseDetail();
        try
        {
            lobj_SubscriptionPurchaseDetail.PurchaseStatus = FCIStorePurchaseStatus.Succeeded;
            lobj_SubscriptionPurchaseDetail.ExtendedErrorMessage = string.Empty;
            lobj_SubscriptionPurchaseDetail.ProductToPurchaseWasFound = true;

            //This gets the product to purchase
            var tobj_StoreProduct = await GetSubscriptionProductAsync(ps_SubscriptionStoreId);

            if (tobj_StoreProduct == null)
            {
                lobj_SubscriptionPurchaseDetail.ExtendedErrorMessage = "The add-on to purchase was not found. Product ID: " + ps_SubscriptionStoreId;
                lobj_SubscriptionPurchaseDetail.ProductToPurchaseWasFound = false;
            }
            else
            {
                //Get the store product to purchase
                StorePurchaseResult result = await tobj_StoreProduct.RequestPurchaseAsync();

                //Convert the store namespace string to our string.
                lobj_SubscriptionPurchaseDetail.PurchaseStatus = (FCIStorePurchaseStatus)Enum.Parse(typeof(FCIStorePurchaseStatus), result.Status.ToString());

                // Capture the error message for the operation, if any.
                if (result.ExtendedError != null)
                {
                    lobj_SubscriptionPurchaseDetail.ExtendedErrorMessage += " " + result.ExtendedError.Message;
                }
            }
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }
        return lobj_SubscriptionPurchaseDetail;
    }

    /// <summary>
    /// This returns the product we will use to call the RequestPurchaseAsync function on
    /// </summary>
    /// <param name="ps_SubscriptionStoreId">The ID if the subscription to purchase</param>
    /// <returns>StoreProduct which represents subscritpion to purchase.</returns>
    private async Task<StoreProduct> GetSubscriptionProductAsync(string ps_SubscriptionStoreId)
    {
        try
        {
            if (context == null)
            {
                context = StoreContext.GetDefault();
                // If your app is a desktop app that uses the Desktop Bridge, you
                // may need additional code to configure the StoreContext object.
                // For more info, see https://aka.ms/storecontext-for-desktop.
            }

            // Load the sellable add-ons for this app and check if the trial is still
            // available for this customer. If they previously acquired a trial they won't
            // be able to get a trial again, and the StoreProduct.Skus property will
            // only contain one SKU.
            StoreProductQueryResult result = await context.GetAssociatedStoreProductsAsync(iobj_filterList);

            if (result.ExtendedError != null)
            {
                throw new Exception("Something went wrong while getting the add-ons from the store. ExtendedError:" + result.ExtendedError);
            }

            // Look for the product that represents the subscription and return it if found - this is what we
            //will purchase
            foreach (var item in result.Products)
            {
                StoreProduct product = item.Value;
                if (product.StoreId == ps_SubscriptionStoreId)
                {
                    return product;
                }
            }

            //If we get here the subscription was not found.  We will return null and the calling function will know the
            //subscription was not found.
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }

        return null;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            context = null;
        }
    }
    #endregion
}
}
</code>```

答:
Currently, there is no such API from StoreContext that could get the information about whether the user disables auto-renew for the subscription.

When users have purchased a subscription add-on, it will renew automatically by default. Detailed messages are listed here: Subscription renewals and grace periods. If users need to check subscription mode, he still need to check it from the account service site.

Body:
I have a Xamarin Forms UWP app.  I am trying to provide more specific information to users of my app regarding their subscription expiration / renewal.  I would like to be able to tell if they have turned off recurring billing for the subscription.  Below are the details I get back from the store regarding the current subscription.  I assume the isActive will turn to false after they turn off recurring billing AND cancel the subscription after Expiration date.  However, in my testing I have found that if they turn off recurring billing and are still within the the subscription period of their last recurring purchase (i.e. the expiration date is still in the future), everything seems to look exactly as if they have recurring billing turned on and the subscription will auto-renew.  I am trying find a way to let them know that their current subscription will expire on a specific date versus will auto-renew on a specific date.  Am I missing something?

Here is the code -- Everything works fine I just don't see anything in the object returned from the Microsoft Store API that indicates if recurring billing is on for the subscription.

using FCISharedAll;
using FCISuite.UWP;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.Services.Store;
using static FCISharedAll.FCIEnums.FlexEnums;

[assembly: Xamarin.Forms.Dependency(typeof(UWPSubscriptionManager))]
namespace FCISuite.UWP
{

public class UWPSubscriptionManager : IFCISubcriptionManager, IDisposable
{
    private StoreContext context = null;
    private static string[] ia_productKinds = { "Durable", "Consumable", "UnmanagedConsumable" };
    private List<String> iobj_filterList = null;

    //We need a constructor to load the list
    public UWPSubscriptionManager()
    {
        iobj_filterList = new List<string>(ia_productKinds);
    }

    ///
    /// This will run at the start of the app to get the active subscription info for the user.
    ///
    /// <returns></returns>
    public async Task<ActiveSubscriptionDetails> GetActiveSubscriptionInformation(ActiveSubscriptionDetails pobj_SubscriptionData)
    {
        string ls_Result = string.Empty;
        try
        {
            if (context == null)
            {
                context = StoreContext.GetDefault();
                // If your app is a desktop app that uses the Desktop Bridge, you
                // may need additional code to configure the StoreContext object.
                // For more info, see https://aka.ms/storecontext-for-desktop.
            }

            StoreAppLicense appLicense = await context.GetAppLicenseAsync();

            // Check if the customer has the rights to the subscription.
            foreach (var addOnLicense in appLicense.AddOnLicenses)
            {
                StoreLicense license = addOnLicense.Value;
                if (license.IsActive)
                {
                    pobj_SubscriptionData.ActiveSubscriptionID = license.SkuStoreId;
                    pobj_SubscriptionData.SubscriptionEndDate = license.ExpirationDate.DateTime;
                }
            }
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }
        //Debug.WriteLine("End of Subscription Info");

        return pobj_SubscriptionData;
    }

    #region get available subscriptions
    public async Task<List<SubscriptionDetail>> GetAvailableSubscriptions(string ps_ProductNotFoundMessage,
        string ps_StoreAddOnsNotFound, string ps_EnvironmentPrefix)
    {
        string ls_Result = "";
        List<SubscriptionDetail> lobj_AvailableSubscriptions = new List<SubscriptionDetail>();

        try
        {
            if (context == null)
            {
                context = StoreContext.GetDefault();
                // If your app is a desktop app that uses the Desktop Bridge, you
                // may need additional code to configure the StoreContext object.
                // For more info, see https://aka.ms/storecontext-for-desktop.
            }

            // Get app store product details. Because this might take several moments,
            // display a ProgressRing during the operation.
            StoreProductResult product_queryResult = await context.GetStoreProductForCurrentAppAsync();

            if (product_queryResult.Product == null)
            {
                // Show additional error info if it is available.
                if (product_queryResult.ExtendedError != null)
                {
                    ls_Result += $"\nExtendedError: {product_queryResult.ExtendedError.Message}";
                }

                // The Store catalog returned an unexpected result.
                throw new Exception(ps_ProductNotFoundMessage + " " + ls_Result);
            }
            else
            {
                StoreProductQueryResult addon_queryResult = await context.GetAssociatedStoreProductsAsync(iobj_filterList);

                if (addon_queryResult.ExtendedError != null)
                {
                    // The user may be offline or there might be some other server failure.
                    ls_Result = $"ExtendedError: {addon_queryResult.ExtendedError.Message}";

                    // The Store catalog returned an unexpected result for the Add-ons.
                    throw new Exception(ps_StoreAddOnsNotFound + " " + ls_Result);
                }
                List<KeyValuePair<string, StoreProduct>> lobj_ProductsforEnvironment = new List<KeyValuePair<string, StoreProduct>>();

                //We are in test - do not show the production subscriptions
                lobj_ProductsforEnvironment = (from tobj_Product in addon_queryResult.Products
                                               where tobj_Product.Value.Title.ToUpper().StartsWith(ps_EnvironmentPrefix.ToUpper())
                                               select tobj_Product).ToList();

                //foreach (KeyValuePair<string, StoreProduct> item in addon_queryResult.Products)
                foreach (KeyValuePair<string, StoreProduct> item in lobj_ProductsforEnvironment)
                {
                    // Add the store product's skus to the list
                    foreach (StoreSku lobj_Sku in item.Value.Skus)
                    {
                        if (lobj_Sku.IsSubscription)
                        {
                            lobj_AvailableSubscriptions.Add(new SubscriptionDetail()
                            {
                                SubscriptionID = item.Value.StoreId,
                                SubscriptionName = lobj_Sku.Title,
                                SubscriptionFormattedPrice = lobj_Sku.Price.FormattedPrice,
                                // Use the sku.SubscriptionInfo property to get info about the subscription.
                                // For example, the following code gets the units and duration of the
                                // subscription billing period.
                                SubscriptionPeriodUnit = lobj_Sku.SubscriptionInfo.BillingPeriodUnit.ToString(),
                                SubscriptionPeriod = lobj_Sku.SubscriptionInfo.BillingPeriod,
                            });
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }
        return lobj_AvailableSubscriptions;
    }
    #endregion

    #region Subscription Purchase area
    ///
    /// This will get the product for the ID from the store, then request to purchase it for the user.
    ///
    /// <param name="ps_SubscriptionStoreId">The ID of the store subscription to be purchased</param>
    /// <returns>boolean that indicates if the purchase succeeded or failed.</returns>
    public async Task<SubscriptionPurchaseDetail> PurchaseSubscription(string ps_SubscriptionStoreId)
    {
        SubscriptionPurchaseDetail lobj_SubscriptionPurchaseDetail = new SubscriptionPurchaseDetail();
        try
        {
            lobj_SubscriptionPurchaseDetail.PurchaseStatus = FCIStorePurchaseStatus.Succeeded;
            lobj_SubscriptionPurchaseDetail.ExtendedErrorMessage = string.Empty;
            lobj_SubscriptionPurchaseDetail.ProductToPurchaseWasFound = true;

            //This gets the product to purchase
            var tobj_StoreProduct = await GetSubscriptionProductAsync(ps_SubscriptionStoreId);

            if (tobj_StoreProduct == null)
            {
                lobj_SubscriptionPurchaseDetail.ExtendedErrorMessage = "The add-on to purchase was not found. Product ID: " + ps_SubscriptionStoreId;
                lobj_SubscriptionPurchaseDetail.ProductToPurchaseWasFound = false;
            }
            else
            {
                //Get the store product to purchase
                StorePurchaseResult result = await tobj_StoreProduct.RequestPurchaseAsync();

                //Convert the store namespace string to our string.
                lobj_SubscriptionPurchaseDetail.PurchaseStatus = (FCIStorePurchaseStatus)Enum.Parse(typeof(FCIStorePurchaseStatus), result.Status.ToString());

                // Capture the error message for the operation, if any.
                if (result.ExtendedError != null)
                {
                    lobj_SubscriptionPurchaseDetail.ExtendedErrorMessage += " " + result.ExtendedError.Message;
                }
            }
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }
        return lobj_SubscriptionPurchaseDetail;
    }

    ///
    /// This returns the product we will use to call the RequestPurchaseAsync function on
    ///
    /// <param name="ps_SubscriptionStoreId">The ID if the subscription to purchase</param>
    /// <returns>StoreProduct which represents subscritpion to purchase.</returns>
    private async Task<StoreProduct> GetSubscriptionProductAsync(string ps_SubscriptionStoreId)
    {
        try
        {
            if (context == null)
            {
                context = StoreContext.GetDefault();
                // If your app is a desktop app that uses the Desktop Bridge, you
                // may need additional code to configure the StoreContext object.
                // For more info, see https://aka.ms/storecontext-for-desktop.
            }

            // Load the sellable add-ons for this app and check if the trial is still
            // available for this customer. If they previously acquired a trial they won't
            // be able to get a trial again, and the StoreProduct.Skus property will
            // only contain one SKU.
            StoreProductQueryResult result = await context.GetAssociatedStoreProductsAsync(iobj_filterList);

            if (result.ExtendedError != null)
            {
                throw new Exception("Something went wrong while getting the add-ons from the store. ExtendedError:" + result.ExtendedError);
            }

            // Look for the product that represents the subscription and return it if found - this is what we
            //will purchase
            foreach (var item in result.Products)
            {
                StoreProduct product = item.Value;
                if (product.StoreId == ps_SubscriptionStoreId)
                {
                    return product;
                }
            }

            //If we get here the subscription was not found.  We will return null and the calling function will know the
            //subscription was not found.
        }
        catch (Exception ex)
        {
            SharedErrorHandler.ProcessException(ex);
        }

        return null;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            context = null;
        }
    }
    #endregion
}
}


问:
Conjunction for Verb Phrase on GF

Problem

I'm trying to generate the sentence  It's sunny on Monday and rainy on Tuesday on GF using RGL. I looked for a method to generate this sentence on the RGL page, but I couldn't find anything that might help with this. Checked Extend.gf on GitHub for more information about GF, and I found these three lines:

    MkVPS      : Temp -> Pol -> VP -> VPS ;  -- hasn't slept
    ConjVPS    : Conj -> [VPS] -> VPS ;      -- has walked and won't sleep
    PredVPS    : NP   -> VPS -> S ;          -- she [has walked and won't sleep]
```
<p>They seemed promising at first glance, but when I tried implementing them on a real code, it seems like I misused <code>[VPS]</code>. My code:</p>
<pre class="lang-hs prettyprint-override"><code>mkPhr(PredVPS
        (it_NP)
        (ConjVPS
            (and_Conj)
            (MkVPS
                (mkTemp (futureTense) (simultaneousAnt))
                (positivePol)
                (mkVP
                    (mkVP (mkA "sunny"))
                    (SyntaxEng.mkAdv (on_Prep) (mkNP (mkN ("Monday"))))))
            (MkVPS
                (mkTemp (futureTense) (simultaneousAnt))
                (positivePol)
                (mkVP
                    (mkVP (mkA "rainy"))
                    (SyntaxEng.mkAdv (on_Prep) (mkNP (mkN ("Tuesday"))))))));
</code>```

But I ran into this error, which obviously a problem with the defined variable and the expected one.

```<code>missing record fields: s1, s2 type of MkVPS (mkTemp futureTense simultaneousAnt) positivePol (AdvVP ((\a -> UseComp (CompAP (PositA a))) (regA "rainy")) (PrepNP on_Prep ((\n -> MassNP (UseN n)) (regN "Monday"))))
      expected: {s1 : ResEng.Agr => Str; s2 : ResEng.Agr => Str}
      inferred: {s : ResEng.Agr => Str; lock_VPS : {}}
</code>```

Question

What is the correct way to use [VPS]?

答:
Clarification on lists

Just like with other list categories C, you need to use a constructor that takes two (or more) Cs and creates a [C].

For categories that are in the RGL API, there are convenience opers of type mkC : Conj -> C -> C -> C, but under the hood, those opers also need to call the proper constructors for [C]. (The constructors are called BaseC and ConsC, and you can read more on lists here.)

How to use conjunctions with VPSs

So VPS is not in the API, so there is no convenience oper with type signature Conj -> VPS -> VPS -> VPS. Instead, you need to call BaseVPS explicitly. Here is working code, I cut your long expression into smaller pieces.

resource VPS = open SyntaxEng, ParadigmsEng, ExtendEng in {
  oper
    -- Lexicon
    sunny_A : A = mkA "sunny" ;
    rainy_A : A = mkA "rainy" ;
    monday_N : N  = mkN "Monday" ;
    tuesday_N : N  = mkN "Tuesday" ;

    -- Helper functions
    adj_on_day : A -> N -> VP = \a,n ->
      mkVP (mkVP a) (SyntaxEng.mkAdv on_Prep (mkNP n)) ;
    sunny_on_Monday_VP  : VP = adj_on_day sunny_A monday_N ;
    rainy_on_Tuesday_VP : VP = adj_on_day rainy_A tuesday_N ;

    tenseVPS : Tense -> VP -> VPS = \tns,vp ->
      MkVPS (mkTemp tns simultaneousAnt) positivePol vp ;
    futureVPS = tenseVPS futureTense ;
    pastVPS = tenseVPS pastTense ;

    -- Constructing the phrase
    -- lin: "it will be sunny on Monday and will be rainy on Tuesday"
    futFutPhrase : Phr =
      mkPhr (
        PredVPS it_NP
                (ConjVPS -- : Conj -> [VPS] -> VPS
                   and_Conj -- : Conj
                   (BaseVPS -- : VPS -> VPS -> [VPS]
                     (futureVPS sunny_on_Monday_VP)  -- : VPS
                     (futureVPS rainy_on_Tuesday_VP) -- : VPS
                   )
                )
      ) ;

    -- lin: "it was sunny on Monday and will be rainy on Tuesday"
    pastFutPhrase : Phr =
      mkPhr (
        PredVPS it_NP
                (ConjVPS -- : Conj -> [VPS] -> VPS
                   and_Conj -- : Conj
                   (BaseVPS -- : VPS -> VPS -> [VPS]
                     (pastVPS sunny_on_Monday_VP)    -- : VPS
                     (futureVPS rainy_on_Tuesday_VP) -- : VPS
                   )
                )
      ) ;
}
```
<p>And it works like this:</p>
```$ gf
Languages:
> i -retain VPS.gf
> cc -one futFutPhrase
it will be sunny on Monday and will be rainy on Tuesday
> cc -one pastFutPhrase
it was sunny on Monday and will be rainy on Tuesday
```
<p>So the tenses are repeated in both cases, because the conjunction is on the VPS level, not on the AP level.</p>
<h2>How to create the phrase you wanted</h2>
<p>If you want to have ellipsis, "it will be sunny on Monday and rainy on Tuesday", you will need to attach the Adv "on Monday" to the AP "sunny" using AdvAP, then do an AP conjunction, turn that AP into VP, and then use that VP in a Cl as you normally would. Here is code, a separate file from the previous:</p>
<pre class="lang-hs prettyprint-override"><code>resource APConj = open SyntaxEng, ParadigmsEng, (A=AdjectiveEng) in {
  oper
    -- Lexicon
    sunny_A : A = mkA "sunny" ;
    rainy_A : A = mkA "rainy" ;
    monday_N : N  = mkN "Monday" ;
    tuesday_N : N  = mkN "Tuesday" ;

    -- Helper functions
    adj_on_day : A -> N -> AP = \a,n ->
      A.AdvAP (mkAP a) (SyntaxEng.mkAdv on_Prep (mkNP n)) ;
    sunny_on_Monday_AP  : AP = adj_on_day sunny_A monday_N ;
    rainy_on_Tuesday_AP : AP = adj_on_day rainy_A tuesday_N ;

    -- Constructing the phrase

    sunnyRainyEllipsisPhrase : Phr =
      mkPhr (
        mkCl (
          mkVP (mkAP and_Conj sunny_on_Monday_AP rainy_on_Tuesday_AP)
          )
      ) ;
}
</code>```

Works like this:

```<code>$ gf
Languages:
> i -retain APConj.gf
> cc -one sunnyRainyEllipsisPhrase
it is sunny on Monday and rainy on Tuesday
</code>```

Title: Conjunction for Verb Phrase on GF

Body:
Problem

I'm trying to generate the sentence  It's sunny on Monday and rainy on Tuesday on GF using RGL. I looked for a method to generate this sentence on the RGL page, but I couldn't find anything that might help with this. Checked Extend.gf on GitHub for more information about GF, and I found these three lines:

    MkVPS      : Temp -> Pol -> VP -> VPS ;  -- hasn't slept
    ConjVPS    : Conj -> [VPS] -> VPS ;      -- has walked and won't sleep
    PredVPS    : NP   -> VPS -> S ;          -- she [has walked and won't sleep]

They seemed promising at first glance, but when I tried implementing them on a real code, it seems like I misused [VPS]. My code:

mkPhr(PredVPS
        (it_NP)
        (ConjVPS
            (and_Conj)
            (MkVPS
                (mkTemp (futureTense) (simultaneousAnt))
                (positivePol)
                (mkVP
                    (mkVP (mkA "sunny"))
                    (SyntaxEng.mkAdv (on_Prep) (mkNP (mkN ("Monday"))))))
            (MkVPS
                (mkTemp (futureTense) (simultaneousAnt))
                (positivePol)
                (mkVP
                    (mkVP (mkA "rainy"))
                    (SyntaxEng.mkAdv (on_Prep) (mkNP (mkN ("Tuesday"))))))));

But I ran into this error, which obviously a problem with the defined variable and the expected one.

missing record fields: s1, s2 type of MkVPS (mkTemp futureTense simultaneousAnt) positivePol (AdvVP ((\a -> UseComp (CompAP (PositA a))) (regA "rainy")) (PrepNP on_Prep ((\n -> MassNP (UseN n)) (regN "Monday"))))
      expected: {s1 : ResEng.Agr => Str; s2 : ResEng.Agr => Str}
      inferred: {s : ResEng.Agr => Str; lock_VPS : {}}

Question

What is the correct way to use [VPS]?

Body:
Clarification on lists

Just like with other list categories C, you need to use a constructor that takes two (or more) Cs and creates a [C].

For categories that are in the RGL API, there are convenience opers of type mkC : Conj -> C -> C -> C, but under the hood, those opers also need to call the proper constructors for [C]. (The constructors are called BaseC and ConsC, and you can read more on lists here.)

How to use conjunctions with VPSs

So VPS is not in the API, so there is no convenience oper with type signature Conj -> VPS -> VPS -> VPS. Instead, you need to call BaseVPS explicitly. Here is working code, I cut your long expression into smaller pieces.

resource VPS = open SyntaxEng, ParadigmsEng, ExtendEng in {
  oper
    -- Lexicon
    sunny_A : A = mkA "sunny" ;
    rainy_A : A = mkA "rainy" ;
    monday_N : N  = mkN "Monday" ;
    tuesday_N : N  = mkN "Tuesday" ;

    -- Helper functions
    adj_on_day : A -> N -> VP = \a,n ->
      mkVP (mkVP a) (SyntaxEng.mkAdv on_Prep (mkNP n)) ;
    sunny_on_Monday_VP  : VP = adj_on_day sunny_A monday_N ;
    rainy_on_Tuesday_VP : VP = adj_on_day rainy_A tuesday_N ;

    tenseVPS : Tense -> VP -> VPS = \tns,vp ->
      MkVPS (mkTemp tns simultaneousAnt) positivePol vp ;
    futureVPS = tenseVPS futureTense ;
    pastVPS = tenseVPS pastTense ;

    -- Constructing the phrase
    -- lin: "it will be sunny on Monday and will be rainy on Tuesday"
    futFutPhrase : Phr =
      mkPhr (
        PredVPS it_NP
                (ConjVPS -- : Conj -> [VPS] -> VPS
                   and_Conj -- : Conj
                   (BaseVPS -- : VPS -> VPS -> [VPS]
                     (futureVPS sunny_on_Monday_VP)  -- : VPS
                     (futureVPS rainy_on_Tuesday_VP) -- : VPS
                   )
                )
      ) ;

    -- lin: "it was sunny on Monday and will be rainy on Tuesday"
    pastFutPhrase : Phr =
      mkPhr (
        PredVPS it_NP
                (ConjVPS -- : Conj -> [VPS] -> VPS
                   and_Conj -- : Conj
                   (BaseVPS -- : VPS -> VPS -> [VPS]
                     (pastVPS sunny_on_Monday_VP)    -- : VPS
                     (futureVPS rainy_on_Tuesday_VP) -- : VPS
                   )
                )
      ) ;
}

And it works like this:

$ gf
Languages:
> i -retain VPS.gf
> cc -one futFutPhrase
it will be sunny on Monday and will be rainy on Tuesday
> cc -one pastFutPhrase
it was sunny on Monday and will be rainy on Tuesday

So the tenses are repeated in both cases, because the conjunction is on the VPS level, not on the AP level.

How to create the phrase you wanted

If you want to have ellipsis, "it will be sunny on Monday and rainy on Tuesday", you will need to attach the Adv "on Monday" to the AP "sunny" using AdvAP, then do an AP conjunction, turn that AP into VP, and then use that VP in a Cl as you normally would. Here is code, a separate file from the previous:

resource APConj = open SyntaxEng, ParadigmsEng, (A=AdjectiveEng) in {
  oper
    -- Lexicon
    sunny_A : A = mkA "sunny" ;
    rainy_A : A = mkA "rainy" ;
    monday_N : N  = mkN "Monday" ;
    tuesday_N : N  = mkN "Tuesday" ;

    -- Helper functions
    adj_on_day : A -> N -> AP = \a,n ->
      A.AdvAP (mkAP a) (SyntaxEng.mkAdv on_Prep (mkNP n)) ;
    sunny_on_Monday_AP  : AP = adj_on_day sunny_A monday_N ;
    rainy_on_Tuesday_AP : AP = adj_on_day rainy_A tuesday_N ;

    -- Constructing the phrase

    sunnyRainyEllipsisPhrase : Phr =
      mkPhr (
        mkCl (
          mkVP (mkAP and_Conj sunny_on_Monday_AP rainy_on_Tuesday_AP)
          )
      ) ;
}

Works like this:

$ gf
Languages:
> i -retain APConj.gf
> cc -one sunnyRainyEllipsisPhrase
it is sunny on Monday and rainy on Tuesday


问:
Need two fields together to be unique
Say I have a model like this:

```<code>class Book(models.Model):

    user = models.ForeignKey(User)
    book_isbn = models.CharField()
</code>```

I would like the combination of the book and user fields to be unique. That is different users could have the same book, but a specific user could only have the book once in their list of books.

I thought unique_together would be the perfect solution, but them read it can't be used if any of the fields have a FK. What's the best way to achieve what I want?

答: I'm currently using multiple django models with unique_together clause which contained foreign keys and I never had any problems. I currently using django 1.2.

Title: Need two fields together to be unique

Body:
Say I have a model like this:

class Book(models.Model):

    user = models.ForeignKey(User)
    book_isbn = models.CharField()

I would like the combination of the book and user fields to be unique. That is different users could have the same book, but a specific user could only have the book once in their list of books.

I thought unique_together would be the perfect solution, but them read it can't be used if any of the fields have a FK. What's the best way to achieve what I want?


问:
OBIEE Column Formula To Create Unique
Asking an OBIEE analysis question.

We have a serialized inventory SA and we have an analysis that shows our entire stock with several columns of information. However, some items have been added to our inventory that are not serialized so the column for serial numbers is blank. No problem, I just added a formula to the serial column so if the serial is null, just replace it with a word or number (right now I have it set to 0) but another issue rose up. You see, since our inventory was previously serialized-only items, we had a quantity column that reported 1 for each of these unique items. Now with non-serialized items in our inventory, the quantity might be something other than 1.
This creates an issue since we usually pull this analysis into a CSV and import to an arcane system that reads each line as one single unique item.

Is there any formula I can use in the serial number column that can perhaps see that the quantity is 4 and just create 4 lines in the analysis for this non-serialized item with pseudo serial numbers such as noserial 0, noserial1, noserial2, and noserial3? This way, each line is still a unique serial number for each physical item we have in our inventory.

shelf
item
serial
quantity

Shelf12
ARMCPU
ARM3020
1

Shelf12
ARMCPU
ARM1231
1

Shelf12
ARMCPU
ARM1299
1

Shelf15
INTELCPU
INT1221
1

Shelf17
AMDCPU
AMD9282
1

Shelf17
AMDCPU
AMD8742
1

Shelf19
100CAP
0
2

Shelf20
080CAP
0
8

The above is how it looks like now. How I would ideally like it be is:

shelf
item
serial
quantity

Shelf17
AMDCPU
AMD8742
1

Shelf19
100CAP
NOSER00
1

Shelf19
100CAP
NOSER01
1

Shelf20
080CAP
NOSER02
1

Shelf20
080CAP
NOSER03
1

Shelf20
080CAP
NOSER04
1

Shelf20
080CAP
NOSER05
1

Shelf20
080CAP
NOSER06
1

Shelf20
080CAP
NOSER07
1

Shelf20
080CAP
NOSER08
1

Shelf20
080CAP
NOSER09
1

Thank you.

答:
Not sure how is the underlying aggregation in the analysis.

This should create a different serial for each NULL entry.

Use RSUM(1) in the calculated column.

Ex.: IFNULL("SERIAL",'NOSERIAL'||CAST(RSUM(1) as CHAR(10))

Title: OBIEE Column Formula To Create Unique


问:
which authentication encryption type is recommanded?
from the dev document, i got that opengauss support several encryption type for cleint authentication:

md5

sha256 (as default)

local is a Unix domain socket. host is a common or SSL-encrypted TCP/IP socket. hostssl is an SSL-encrypted TCP/IP socket. hostnossl is a TCP/IP-only socket.
authmehod-options is an optional parameter. Value range:

As i know that md5 is not safe enough?
so why opengauss still support it, which authentication encryption type is recommanded ?

答:
Use MD5 only for compatibility with legacy applications and data.
Sha256 is recommanded.</p>


问:
Update String column in DynamoDB
I'm new to DynamoDB and was following tutorial to implement basic CRUD operations.

I have the below code

```<code>public static void main(String ... args) throws Exception {

    //1. create client
    client = AmazonDynamoDBClientBuilder.standard()
            .withRegion(Regions.US_EAST_1)
            .build();

    //2. Create table
    String jobID="8aee43e5c44212040529fe11000117cdd0cb77eb";
    PutItemSpec putItemSpec = new PutItemSpec();
    putItemSpec.withItem(new Item().withPrimaryKey("jobid", jobID ).
            withString("type", "first").withBoolean("cancel", false));
    PutItemOutcome putItemOutcome = table.putItem(putItemSpec);
    System.out.println(putItemOutcome);

    //3. Read
    GetItemSpec spec = new GetItemSpec().withPrimaryKey("jobid", jobID);
    Item item = table.getItem(spec);
    System.out.println(item);

    //4.Update boolean
    UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("jobid", jobID)
            .withUpdateExpression("set cancel=:s")
            .withValueMap(new ValueMap().withBoolean(":s",true));
    UpdateItemOutcome updateItemOutcome = table.updateItem(updateItemSpec);

    //4. read updated bool
    item = table.getItem(spec);
    System.out.println(item);

    //5. update String breaks
    UpdateItemSpec updateItemSpec2 = new UpdateItemSpec().withPrimaryKey("jobid", jobID)
            .withUpdateExpression("set type=:s")
            .withValueMap(new ValueMap().withString(":s","updated"));
    UpdateItemOutcome updateItemOutcome2 = table.updateItem(updateItemSpec2);

    //4. read updated bool
    item = table.getItem(spec);
    System.out.println(item);
}}
</code>```

In this code, Create works fine and getItem fetches the data. When I updated the cancel boolean column it works fine and returns the updated Item. However, when I try to update the String column type to different value it throws the following exception.

```<code>Exception in thread "main" com.amazonaws.AmazonServiceException: Unable to unmarshall exception response with the unmarshallers provided (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 4RHDOGACM1MOADU4N8RUPFMUJBVV4KQNSO5AEMVJF66Q9ASUAAJG; Proxy: null)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1862)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1415)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1384)
</code>```

The AWS-SDK-Version is 1.12.153 and JDK Version is 17.0.1.  Also, when I add new string column type2 as part of the update and update it with another call it works. But, String column added as part of create is not getting updated.

Please let me know what I'm missing?

Thanks!

答:
The word type is one of many DynamoDB reserved words.

You cannot use a reserved word in an expression. Instead you need to use an alias and then provide DynamoDB with a map from the alias to the real name. For example you might indicate an alias by set #t=:s and then provide a map from #t to type.

Your code will look something like this:

```<code>UpdateItemSpec updateItemSpec2 =
    new UpdateItemSpec()
        .withPrimaryKey("jobid", jobID)
        .withUpdateExpression("set #t=:s")
        .withValueMap(new ValueMap().withString(":s","updated"))
        .withNameMap(new NameMap().with("#t","type"));
</code>```

Title: Update String column in DynamoDB

Body:
I'm new to DynamoDB and was following tutorial to implement basic CRUD operations.

I have the below code

public static void main(String ... args) throws Exception {

    //1. create client
    client = AmazonDynamoDBClientBuilder.standard()
            .withRegion(Regions.US_EAST_1)
            .build();

    //2. Create table
    String jobID="8aee43e5c44212040529fe11000117cdd0cb77eb";
    PutItemSpec putItemSpec = new PutItemSpec();
    putItemSpec.withItem(new Item().withPrimaryKey("jobid", jobID ).
            withString("type", "first").withBoolean("cancel", false));
    PutItemOutcome putItemOutcome = table.putItem(putItemSpec);
    System.out.println(putItemOutcome);

    //3. Read
    GetItemSpec spec = new GetItemSpec().withPrimaryKey("jobid", jobID);
    Item item = table.getItem(spec);
    System.out.println(item);

    //4.Update boolean
    UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("jobid", jobID)
            .withUpdateExpression("set cancel=:s")
            .withValueMap(new ValueMap().withBoolean(":s",true));
    UpdateItemOutcome updateItemOutcome = table.updateItem(updateItemSpec);

    //4. read updated bool
    item = table.getItem(spec);
    System.out.println(item);

    //5. update String breaks
    UpdateItemSpec updateItemSpec2 = new UpdateItemSpec().withPrimaryKey("jobid", jobID)
            .withUpdateExpression("set type=:s")
            .withValueMap(new ValueMap().withString(":s","updated"));
    UpdateItemOutcome updateItemOutcome2 = table.updateItem(updateItemSpec2);

    //4. read updated bool
    item = table.getItem(spec);
    System.out.println(item);
}}

In this code, Create works fine and getItem fetches the data. When I updated the cancel boolean column it works fine and returns the updated Item. However, when I try to update the String column type to different value it throws the following exception.

Exception in thread "main" com.amazonaws.AmazonServiceException: Unable to unmarshall exception response with the unmarshallers provided (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 4RHDOGACM1MOADU4N8RUPFMUJBVV4KQNSO5AEMVJF66Q9ASUAAJG; Proxy: null)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1862)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1415)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1384)

The AWS-SDK-Version is 1.12.153 and JDK Version is 17.0.1.  Also, when I add new string column type2 as part of the update and update it with another call it works. But, String column added as part of create is not getting updated.

Please let me know what I'm missing?

Thanks!

Body:
The word type is one of many DynamoDB reserved words.

You cannot use a reserved word in an expression. Instead you need to use an alias and then provide DynamoDB with a map from the alias to the real name. For example you might indicate an alias by set #t=:s and then provide a map from #t to type.

Your code will look something like this:

UpdateItemSpec updateItemSpec2 =
    new UpdateItemSpec()
        .withPrimaryKey("jobid", jobID)
        .withUpdateExpression("set #t=:s")
        .withValueMap(new ValueMap().withString(":s","updated"))
        .withNameMap(new NameMap().with("#t","type"));


问:
When i use `json_arrayagg` & `json_object` with inner join in MySQL, Why are the results repeated?
resumes table

```<code>CREATE TABLE if not exists resumes (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        title VARCHAR(100) NOT NULL,
        content VARCHAR(255),
        user_id BIGINT UNSIGNED NOT NULL,

        PRIMARY KEY (id),
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
      );
</code>```

educations, careers tables

```<code>CREATE TABLE if not exists educations (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        type VARCHAR(20),
        school_name VARCHAR(100),
        resume_id BIGINT UNSIGNED NOT NULL,

        PRIMARY KEY (id),
        FOREIGN KEY (resume_id) REFERENCES resumes(id) ON DELETE CASCADE
      );

      CREATE TABLE if not exists careers (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        company VARCHAR(100),
        department VARCHAR(100),
        resume_id BIGINT UNSIGNED NOT NULL,

        PRIMARY KEY (id),
        FOREIGN KEY (resume_id) REFERENCES resumes(id) ON DELETE CASCADE
      );
</code>```

and insert datas

```<code>INSERT INTO resumes (title, content) VALUES ("this_is_title", "this_is_content"); // id 1

INSERT INTO educations (type, school_name, resume_id) VALUES ("High_School", "This_is_school_name", 1),("College", "This_is_college_name", 1);

INSERT INTO careers (company, department, resume_id) VALUES ("company_1", "software", 1);
</code>```

and now
I want to get educations and careers rows with resume_id of 1.
Like this

```<code>{
 educations: [
  {"type": "highschool", "school_name": "This_is_school_name"},
  {"type": "college", "school_name": "This_is_college_name"}
  ],
 careers: [
 {"company": "company_1", "department": "software"},
 ]
}
</code>```

so i used this query

```<code>SELECT
    json_arrayagg(json_object('type', E.type, 'school_name', E.school_name)) AS educations,
    json_arrayagg(json_object('company', C.company, 'department', C.department)) AS careers
FROM resumes R
inner join educations E
    on E.resume_id = R.id
inner join careers C
    on C.resume_id = R.id
where R.id = 1;
</code>```

but result is

```<code>{
 educations: [
  {"type": "highschool", "school_name": "This_is_school_name"},
  {"type": "college", "school_name": "This_is_college_name"}
  ],
 careers: [
 {"company": "company_1", "department": "software"},
 {"company": "company_1", "department": "software"}
 ]
}
</code>```

why does careers repeat?
help!

edit
I followed this link
How to return distinct values in a JSON_ARRAYAGG

but, results are the same as before.

```<code>SELECT
    json_arrayagg(json_object('company', C.company, 'department', C.department)) AS careers,
    json_arrayagg(json_object('type', E.type, 'school_name', E.school_name)) AS educations
FROM (select distinct * from test0129.resumes) R
inner join test0129.careers C
    on C.resume_id = R.id
inner join test0129.educations E
    on E.resume_id = R.id
where R.id = 1 ;
</code>```

答:
You have to do one of the aggregations in a subquery, otherwise you get a cross product of the careers and educations tables.

```<code>SELECT
    json_arrayagg(json_object('company', C.company, 'department', C.department)) AS careers,
    e.educations
FROM resumes AS R
JOIN careers AS C ON C.resume_id = R.id
JOIN (
    SELECT resume_id, json_arrayagg(json_object('type', E.type, 'school_name', E.school_name)) AS educations
    FROM educations AS E
    GROUP BY resume_id
) AS e ON e.resume_id = R.id
WHERE r.id = 1
</code>```

DEMO

Body:
resumes table

CREATE TABLE if not exists resumes (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        title VARCHAR(100) NOT NULL,
        content VARCHAR(255),
        user_id BIGINT UNSIGNED NOT NULL,

        PRIMARY KEY (id),
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
      );

educations, careers tables

CREATE TABLE if not exists educations (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        type VARCHAR(20),
        school_name VARCHAR(100),
        resume_id BIGINT UNSIGNED NOT NULL,

        PRIMARY KEY (id),
        FOREIGN KEY (resume_id) REFERENCES resumes(id) ON DELETE CASCADE
      );

      CREATE TABLE if not exists careers (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        company VARCHAR(100),
        department VARCHAR(100),
        resume_id BIGINT UNSIGNED NOT NULL,

        PRIMARY KEY (id),
        FOREIGN KEY (resume_id) REFERENCES resumes(id) ON DELETE CASCADE
      );

and insert datas

INSERT INTO resumes (title, content) VALUES ("this_is_title", "this_is_content"); // id 1

INSERT INTO educations (type, school_name, resume_id) VALUES ("High_School", "This_is_school_name", 1),("College", "This_is_college_name", 1);

INSERT INTO careers (company, department, resume_id) VALUES ("company_1", "software", 1);

and now
I want to get educations and careers rows with resume_id of 1.
Like this

{
 educations: [
  {"type": "highschool", "school_name": "This_is_school_name"},
  {"type": "college", "school_name": "This_is_college_name"}
  ],
 careers: [
 {"company": "company_1", "department": "software"},
 ]
}

so i used this query

SELECT
    json_arrayagg(json_object('type', E.type, 'school_name', E.school_name)) AS educations,
    json_arrayagg(json_object('company', C.company, 'department', C.department)) AS careers
FROM resumes R
inner join educations E
    on E.resume_id = R.id
inner join careers C
    on C.resume_id = R.id
where R.id = 1;

but result is

{
 educations: [
  {"type": "highschool", "school_name": "This_is_school_name"},
  {"type": "college", "school_name": "This_is_college_name"}
  ],
 careers: [
 {"company": "company_1", "department": "software"},
 {"company": "company_1", "department": "software"}
 ]
}

why does careers repeat?
help!

edit
I followed this link
How to return distinct values in a JSON_ARRAYAGG

but, results are the same as before.

SELECT
    json_arrayagg(json_object('company', C.company, 'department', C.department)) AS careers,
    json_arrayagg(json_object('type', E.type, 'school_name', E.school_name)) AS educations
FROM (select distinct * from test0129.resumes) R
inner join test0129.careers C
    on C.resume_id = R.id
inner join test0129.educations E
    on E.resume_id = R.id
where R.id = 1 ;

Body:
You have to do one of the aggregations in a subquery, otherwise you get a cross product of the careers and educations tables.

SELECT
    json_arrayagg(json_object('company', C.company, 'department', C.department)) AS careers,
    e.educations
FROM resumes AS R
JOIN careers AS C ON C.resume_id = R.id
JOIN (
    SELECT resume_id, json_arrayagg(json_object('type', E.type, 'school_name', E.school_name)) AS educations
    FROM educations AS E
    GROUP BY resume_id
) AS e ON e.resume_id = R.id
WHERE r.id = 1

DEMO


问:
Inconsistencies with C++11 function signatures
I have questions regarding functions, more specific on function signatures and how to pass them. I might be a trivial or even stupid question, but I couldn't find a satisfying answer yet.

Please consider this example which uses a std::unique_ptr to manage a file pointer:

```<code>#include <iostream>
#include <memory>

void func1(FILE* f)
{
    std::cout << "func1 called" << std::endl;
    fclose(f);
}

int main()
{
    FILE* f = fopen("testfile.txt", "w");
    if(f)
    {
        std::unique_ptr<FILE, void(*)(FILE*)> fptr(f, &func1);
    }

    return 0;
}
</code>```

This kind of smart pointer needs a functions signature as second template argument (shared_ptr does not for some odd reason). My current understanding of interpreting the signature here is

void () (FILE) is a pointer to a function returning nothing (void)
and a filepointer as argument.

As a result, the user has to pass the address of the desired function with the address operator. At this point, a few questions arise:

1.) Removal of the address operator works just as well, no compiler warning is thrown, code works. Shouldn't this be an error/warning?

2.) If I use a reference to a function (e.g. unique_ptr<FILE, void(&)(FILE*)>(f, func1) ) it works as expected, so is this a superior way to pass a function as it is unambiguous?

3.) Removing the middle specifier altogether (e.g. unique_ptr<FILE, void()(FILE*)>(f, func1) ) causes compiler errors, so is passing a function by value impossible in general? (if it is, then it would make sense to overload the version in 1. by implicitly converting the function to a function pointer)

答:
Function name is the always address of function (pointer to the function). If you want to use something else you can use some wrapper, e.g. std::function:

```<code>#include <iostream>
#include <memory>
#include <functional>

class Closer {
public:
    void operator ()(FILE *f) {
        std::cout << "func1 called" << std::endl;
        fclose(f);
    }
};

int main()
{
    FILE* f = fopen("testfile.txt", "w");
    if(f)
    {
        std::unique_ptr<FILE, std::function<void(FILE*)>> fptr(f, Closer());
    }

    return 0;
}
</code>```

Lambda in that case is anonymous functional object.

Body:
I have questions regarding functions, more specific on function signatures and how to pass them. I might be a trivial or even stupid question, but I couldn't find a satisfying answer yet.

Please consider this example which uses a std::unique_ptr to manage a file pointer:

#include <iostream>
#include <memory>

void func1(FILE* f)
{
    std::cout << "func1 called" << std::endl;
    fclose(f);
}

int main()
{
    FILE* f = fopen("testfile.txt", "w");
    if(f)
    {
        std::unique_ptr<FILE, void(*)(FILE*)> fptr(f, &func1);
    }

    return 0;
}

This kind of smart pointer needs a functions signature as second template argument (shared_ptr does not for some odd reason). My current understanding of interpreting the signature here is

void () (FILE) is a pointer to a function returning nothing (void)
and a filepointer as argument.

As a result, the user has to pass the address of the desired function with the address operator. At this point, a few questions arise:

1.) Removal of the address operator works just as well, no compiler warning is thrown, code works. Shouldn't this be an error/warning?

2.) If I use a reference to a function (e.g. unique_ptr<FILE, void(&)(FILE*)>(f, func1) ) it works as expected, so is this a superior way to pass a function as it is unambiguous?

3.) Removing the middle specifier altogether (e.g. unique_ptr<FILE, void()(FILE*)>(f, func1) ) causes compiler errors, so is passing a function by value impossible in general? (if it is, then it would make sense to overload the version in 1. by implicitly converting the function to a function pointer)

Body:
Function name is the always address of function (pointer to the function). If you want to use something else you can use some wrapper, e.g. std::function:

#include <iostream>
#include <memory>
#include <functional>

class Closer {
public:
    void operator ()(FILE *f) {
        std::cout << "func1 called" << std::endl;
        fclose(f);
    }
};

int main()
{
    FILE* f = fopen("testfile.txt", "w");
    if(f)
    {
        std::unique_ptr<FILE, std::function<void(FILE*)>> fptr(f, Closer());
    }

    return 0;
}

Lambda in that case is anonymous functional object.


问:
Creating increment limit
Ok so I am making a like/dislike system for my website and I got it to work. The only problem is, is that a user can like something more than once, how do I stop this? heres my function

```<code>    function thumbup(uid, s) {
        const prevthumbs = s.thumbs

            firebase.db.collection('users').doc(uid).update({
                thumbs: prevthumbs + 1
            })

    }
</code>```

How can I limit the increment to only one?

答:
To limit how often the user can do something, use their UID as the key for the operation.

For example, if you don't have too many users, you can have a field likedBy in the document which is an array of the UIDs of the users who liked this user.

It's a bit unclear how to exactly implement it in your code for me, as you're already writing to a doc(uid), where usually the user is liking a post or something like that.

Title: Creating increment limit

Body:
Ok so I am making a like/dislike system for my website and I got it to work. The only problem is, is that a user can like something more than once, how do I stop this? heres my function

    function thumbup(uid, s) {
        const prevthumbs = s.thumbs

            firebase.db.collection('users').doc(uid).update({
                thumbs: prevthumbs + 1
            })

    }

How can I limit the increment to only one?


问:
Python rglob("*") vs glob("*)
I am trying to move a bunch of files with "V1.2" in the name to an archive folder. It seems to be working fine with the following code:

```<code>for folder in copyPath.glob("*"):
    for subfolder in folder.glob("*"):
        for content in subfolder.glob("*"):
            if "V1.2" in content.name:
                shutil.move(content ,Path(subfolder,"Archive"))
</code>```

However, the following code with rglob("*V1.2*"), python just creates an "Archive" named extentionless file into the archive folder. Why is that?

```<code>for file in copyPath.rglob("*V1.2*"):
    shutil.move(file,Path(file.parent,"Archive"))
</code>```

Regards,
AS

答:
You state that the following code creates a file named "Archive" in the archive folder:

```<code>for file in copyPath.rglob("*V1.2*"):
    shutil.move(file,Path(file.parent,"Archive"))
</code>```

shutil.move only moves your files into a directory if the directory already exists. Otherwise, it'll move (rename) your file. I guess that Path(file.parent, "Archive") is not a directory, so every file matching the condition is moved into a file called "Archive", each file overwriting the previous one.

The fix should be simple:

```<code>for file in copyPath.rglob("*V1.2*"):
    target = Path(file.parent, "Archive")
    if target.is_file():
        raise ValueError(f"Invalid directory: {target} is a file!")  # safety check to avoid overwriting files and data loss

    if not target.is_dir():
        target.mkdir(parents=True)  # <- this should solve your problem

    shutil.move(file, target)
</code>```

Title: Python rglob("*") vs glob("*)

Body:
I am trying to move a bunch of files with "V1.2" in the name to an archive folder. It seems to be working fine with the following code:

for folder in copyPath.glob("*"):
    for subfolder in folder.glob("*"):
        for content in subfolder.glob("*"):
            if "V1.2" in content.name:
                shutil.move(content ,Path(subfolder,"Archive"))

However, the following code with rglob("*V1.2*"), python just creates an "Archive" named extentionless file into the archive folder. Why is that?

for file in copyPath.rglob("*V1.2*"):
    shutil.move(file,Path(file.parent,"Archive"))

Regards,
AS

Body:
You state that the following code creates a file named "Archive" in the archive folder:

for file in copyPath.rglob("*V1.2*"):
    shutil.move(file,Path(file.parent,"Archive"))

shutil.move only moves your files into a directory if the directory already exists. Otherwise, it'll move (rename) your file. I guess that Path(file.parent, "Archive") is not a directory, so every file matching the condition is moved into a file called "Archive", each file overwriting the previous one.

The fix should be simple:

for file in copyPath.rglob("*V1.2*"):
    target = Path(file.parent, "Archive")
    if target.is_file():
        raise ValueError(f"Invalid directory: {target} is a file!")  # safety check to avoid overwriting files and data loss

    if not target.is_dir():
        target.mkdir(parents=True)  # <- this should solve your problem

    shutil.move(file, target)


问:
Converting a int to a BCD byte array
I want to convert an int to a byte[2] array using BCD.

The int in question will come from DateTime representing the Year and must be converted to two bytes.

Is there any pre-made function that does this or can you give me a simple way of doing this?

example:

```<code>int year = 2010
</code>```

would output:

```<code>byte[2]{0x20, 0x10};
</code>```

答:
Use this method.

```<code>    public static byte[] ToBcd(int value){
        if(value<0 || value>99999999)
            throw new ArgumentOutOfRangeException("value");
        byte[] ret=new byte[4];
        for(int i=0;i<4;i++){
            ret[i]=(byte)(value%10);
            value/=10;
            ret[i]|=(byte)((value%10)<<4);
            value/=10;
        }
        return ret;
    }
</code>```

This is essentially how it works.

If the value is less than 0 or greater than 99999999, the value won't fit in four bytes. More formally, if the value is less than 0 or is 10^(n*2) or greater, where n is the number of bytes, the value won't fit in n bytes.

For each byte:

Set that byte to the remainder of the value-divided-by-10 to the byte. (This will place the last digit in the low nibble [half-byte] of the current byte.)

Divide the value by 10.

Add 16 times the remainder of the value-divided-by-10 to the byte. (This will place the now-last digit in the high nibble of the current byte.)

Divide the value by 10.

(One optimization is to set every byte to 0 beforehand -- which is implicitly done by .NET when it allocates a new array -- and to stop iterating when the value reaches 0. This latter optimization is not done in the code above, for simplicity. Also, if available, some compilers or assemblers offer a divide/remainder routine that allows retrieving the quotient and remainder in one division step, an optimization which is not usually necessary though.)

ContentLicense: CC BY-SA 2.5

Title: Converting a int to a BCD byte array

Body:
I want to convert an int to a byte[2] array using BCD.

The int in question will come from DateTime representing the Year and must be converted to two bytes.

Is there any pre-made function that does this or can you give me a simple way of doing this?

example:

int year = 2010

would output:

byte[2]{0x20, 0x10};

Body:
Use this method.

    public static byte[] ToBcd(int value){
        if(value<0 || value>99999999)
            throw new ArgumentOutOfRangeException("value");
        byte[] ret=new byte[4];
        for(int i=0;i<4;i++){
            ret[i]=(byte)(value%10);
            value/=10;
            ret[i]|=(byte)((value%10)<<4);
            value/=10;
        }
        return ret;
    }

This is essentially how it works.

If the value is less than 0 or greater than 99999999, the value won't fit in four bytes. More formally, if the value is less than 0 or is 10^(n*2) or greater, where n is the number of bytes, the value won't fit in n bytes.

For each byte:

Set that byte to the remainder of the value-divided-by-10 to the byte. (This will place the last digit in the low nibble [half-byte] of the current byte.)

Divide the value by 10.

Add 16 times the remainder of the value-divided-by-10 to the byte. (This will place the now-last digit in the high nibble of the current byte.)

Divide the value by 10.

(One optimization is to set every byte to 0 beforehand -- which is implicitly done by .NET when it allocates a new array -- and to stop iterating when the value reaches 0. This latter optimization is not done in the code above, for simplicity. Also, if available, some compilers or assemblers offer a divide/remainder routine that allows retrieving the quotient and remainder in one division step, an optimization which is not usually necessary though.)


问:
Tell if a certain delimeter is in a string
I tried setting a Scanner's delimiter to "\t" (and using the Scanner.hasNext() method) to tell if there was a tab in a String, but it returns true regardless of whether or not the delimiter is in the string. I also tried splitting the string with "\t", but this did not error out, even when there was no tab character. How can you tell if there is a tab?</p>

答:
The Scanner delimiter will effectively remove that from the string; it finds text before and after that delimeter, whether it exists or not.

Similarly, splitting doesn't care if the split pattern exists. However, you could check the size of the list. For example, "foobar".split("-").length is 1, but "foo-bar".split("-").length is 2, indicating the hyphen exists (check boolean exists = string.split(pattern).length > 1).

The better solution for a tab would just be string.contains("\t")


问:
Is there a way to export code to HTML in Eclipse?
I know NetBeans has this feature, but I can't find it in Eclipse. A quick search for plugins was not successful.</p>

答:
Java2Html - Eclipse Plugin:

Convert files:

  Select items in the Package Explorer, Navigator or other views and right click to open the context menu. There is a Java2Html menu item that opens the conversion dialog.

Convert text from a text editor:

  Right click on an editor and choose the Java2Html context menu item to convert the current selected text.

Adjust preferences:

  Colors, tab size, etc. for conversion can be adjusted on the preference pages (Menu "Window" - "Preferences" - "Java" - "Java2Html")...

OwnerDisplayName: Thomasz

LastEditorDisplayName: Eddie

OwnerDisplayName: Greg


问:
How to count Matching values in Array of Javascript
please tell me any good algorithm/code to get list of unique values from array and count of its occurrence in array. (i am using javascript).</p>

答:
I know this is old post but I was lookimg for a simple solution so I figured I'd post what I worked out for anyone still looking into this</p>
```<code>const test = [5, 3, 9, 5, 3, 5, 5]

//This function will return a new array of only the specified value
Array.prototype.unique = function(find) {
return this.filter(x => x == find)
}

//Usage
console.log(test.unique(5)) // returns [5,5,5,5]

//This Function will return the number of occurences in an array
Array.prototype.count = function(find) {
return this.filter(x => x == find).length
}

//Usage
console.log(test.count(5)) // returns 4
</code>```

Body:
I know this is old post but I was lookimg for a simple solution so I figured I'd post what I worked out for anyone still looking into this

const test = [5, 3, 9, 5, 3, 5, 5]

//This function will return a new array of only the specified value
Array.prototype.unique = function(find) {
return this.filter(x => x == find)
}

//Usage
console.log(test.unique(5)) // returns [5,5,5,5]

//This Function will return the number of occurences in an array
Array.prototype.count = function(find) {
return this.filter(x => x == find).length
}

//Usage
console.log(test.count(5)) // returns 4


问:
How'd I properly ampersand separate query string array param and format the URL along with it?
My code's causing some strange behavior and I'm not sure why.

For some reason, the http_build_query($valuesArr, '', '&'); line isn't separating with & and instead it's separating with %.

```<code>$values = $request->get('allValues');

$valuesArr = [
    'valueOne' => $values,
    'valueTwo' => $values
];

http_build_query($valuesArr, '', ','); // separating with `%` instead of `,`

$queryParams = ['allValues' => (object) $valuesArr]; // cast array to object

dd($queryParams);
</code>```

Whenever I do dd($queryParams);, the result is (it's also missing the , to separate valueOne and valueTwo for some reason):

```<code>^ array:2 [
  {
     "valueOne" => "0684857340;0684857340429"
     "valueTwo" => "0684857340;0684857340429"
  }
]
</code>```

How can I make it so that it looks like:

```<code>^ array:2 [
  {
      "valueOne" => "0684857340",
      "valueTwo" => "0684857340429"
  }
]
</code>```

and the final url looks like (and optionally allow one value passed as well):

mySite.test/api?value=0684857340&0684857340429

Output of dd($request->get('allValues'));:

```<code>0684857340&0684857340429
</code>```

答:
If your format is always the same (number & number), then this should work.

```<code>$values = $request->get('allValues');
// string '0684857340&0684857340429'

$keysArray = ['valueOne', 'valueTwo'];
$valuesArray = explode('&', $values);
// array ['0684857340', '0684857340429']

$queryArray = array_combine($keysArray, $valuesArray);
// array ['valueOne' => '0684857340', 'valueTwo' => '0684857340429']

$query = http_build_query($queryArray);
// string 'valueOne=0684857340&valueTwo=0684857340429'
</code>```

If you don't know how many numbers you'll get (number or number & number & number....), then maybe using an array would be better.

```<code>$values = $request->get('allValues');
// string '0684857340&0684857340429'

$valuesArray = explode('&', $values);
// array ['0684857340', '0684857340429']

$queryArray = ['values' => $valuesArray];
// array ['values' => [...]]

$query = http_build_query($queryArray);
// string  'values%5B0%5D=number1&values%5B1%5D=number2&values%5B2%5D=...'
// decoded 'values[0]=number1&values[1]=number2....
</code>```

Body:
My code's causing some strange behavior and I'm not sure why.

For some reason, the http_build_query($valuesArr, '', '&'); line isn't separating with & and instead it's separating with %.

$values = $request->get('allValues');

$valuesArr = [
    'valueOne' => $values,
    'valueTwo' => $values
];

http_build_query($valuesArr, '', ','); // separating with `%` instead of `,`

$queryParams = ['allValues' => (object) $valuesArr]; // cast array to object

dd($queryParams);

Whenever I do dd($queryParams);, the result is (it's also missing the , to separate valueOne and valueTwo for some reason):

^ array:2 [
  {
     "valueOne" => "0684857340;0684857340429"
     "valueTwo" => "0684857340;0684857340429"
  }
]

How can I make it so that it looks like:

^ array:2 [
  {
      "valueOne" => "0684857340",
      "valueTwo" => "0684857340429"
  }
]

and the final url looks like (and optionally allow one value passed as well):

mySite.test/api?value=0684857340&0684857340429

Output of dd($request->get('allValues'));:

0684857340&0684857340429

Body:
If your format is always the same (number & number), then this should work.

$values = $request->get('allValues');
// string '0684857340&0684857340429'

$keysArray = ['valueOne', 'valueTwo'];
$valuesArray = explode('&', $values);
// array ['0684857340', '0684857340429']

$queryArray = array_combine($keysArray, $valuesArray);
// array ['valueOne' => '0684857340', 'valueTwo' => '0684857340429']

$query = http_build_query($queryArray);
// string 'valueOne=0684857340&valueTwo=0684857340429'

If you don't know how many numbers you'll get (number or number & number & number....), then maybe using an array would be better.

$values = $request->get('allValues');
// string '0684857340&0684857340429'

$valuesArray = explode('&', $values);
// array ['0684857340', '0684857340429']

$queryArray = ['values' => $valuesArray];
// array ['values' => [...]]

$query = http_build_query($queryArray);
// string  'values%5B0%5D=number1&values%5B1%5D=number2&values%5B2%5D=...'
// decoded 'values[0]=number1&values[1]=number2....


问:
Create Excel sheet with worksheet_change code
I have code that creates a worksheet and the worksheet contains a table.
I then programmatically add an advanced filter to the table in the created worksheet.
This works fine, but the advanced filter does not refresh on change of the worksheet: A known issue.

The standard solution is to put code behind the worksheet_change event so the filter is refreshed when the worksheet changes.  This also works fine when I add this code manually.

But when I create a sheet I want to automatically create the code for the new sheets worksheet_change event.  I don't know how to programmatically specify code for my new sheet in the worksheet_change event.

Is this possible? Or is there another way to accomplish this?

答:
Maybe look at using this instead.  It'll fire for all sheet changes and allows your code to work centrally ...

```<code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

End Sub
</code>```

Body:
Maybe look at using this instead.  It'll fire for all sheet changes and allows your code to work centrally ...

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

End Sub


问:
How can I popup an edit box (or another modal that can type something) in MFC app when I click a button
I want to popup an edit box or another modal when I click a button. I can type something in this box and when I close it, I will receive the data I've just typed. How can I do?</p>

答:
Most obvious way would be to create a dialog box with one edit control and OK and Cancel buttons (you would probably want to alow user to cancel).

Then you provide a method in that dialog to access typed-in value after it was closed.


问:
Why does "%d" can print out ASCII code not only decimal?
I heard that '%d' prints decimal, but if I import printf("%d",'a'), it prints out a ASCII code of 'a'. I cannot understand why %d which only can print out decimal also prints ASCII code. is ASCII code a decimal?</p>

答:
Computers do not know anything about "decimals". Compueters know numbers. Generally everything is a number in computers. Characters, strings - even machine code instructions.

Humans need numbers to be displayed in an understandable form. We are used to use base 10 numbers called by you "decimals".

Characters are numbers too. We (humans) have invented encodings to know what number represents a particular character. Very popular is ASCII system. When you printf("%d\n", 'A'); then you simple print number representing character 'A' using the base 10 representation.


问:
How can I make a function that prints the number of unique vowels in a string?
I am creating a program that prints the number of unique vowels in a string, whether upper or lower case. For example: "swEet” would print 1. What I have so far prints the number of vowels but not unique ones. What can I change or add to my code to do this? Thank you. I'm a beginner in Python and coding.

```<code>import sys

def count_vowels(sys_str):

    sys_str = sys.argv[1].upper()

    vowels = 'aeiou'

    count = len([c for c in sys_str.lower() if c in
    vowels])

    return count

sys_str = sys.argv[1].upper()
count = count_vowels(sys_str)
print(count)
</code>```

Source: DBrowne's answer at Counting the number of vowels in a string using for loops in Python I got some of my code from this user in this question.

答:
Is there a requirement that you use for loops? The set type is much better suited to this type of problem -- no iteration necessary (at least in Python, there's obviously still iteration on the back end in C).

VOWELS = set("aeiou")

def count_vowels(s: str) -> int:
    return len(VOWELS.intersection(s.lower()))
```
<p>Examples:</p>
<pre class="lang-py prettyprint-override"><code>In [6]: count_vowels("Eat")
Out[6]: 2

In [7]: count_vowels("sweEt")
Out[7]: 1

In [8]: count_vowels("hello")
Out[8]: 2

In [9]: count_vowels("aeiou")
Out[9]: 5

In [10]: count_vowels("aeiou"*10)
Out[10]: 5

In [11]: count_vowels("")
Out[11]: 0

In [12]: count_vowels("syzygy")
Out[12]: 0
</code>```

Body:
I am creating a program that prints the number of unique vowels in a string, whether upper or lower case. For example: "swEet” would print 1. What I have so far prints the number of vowels but not unique ones. What can I change or add to my code to do this? Thank you. I'm a beginner in Python and coding.

import sys

def count_vowels(sys_str):

    sys_str = sys.argv[1].upper()

    vowels = 'aeiou'

    count = len([c for c in sys_str.lower() if c in
    vowels])

    return count

sys_str = sys.argv[1].upper()
count = count_vowels(sys_str)
print(count)

Source: DBrowne's answer at Counting the number of vowels in a string using for loops in Python I got some of my code from this user in this question.

Body:
Is there a requirement that you use for loops? The set type is much better suited to this type of problem -- no iteration necessary (at least in Python, there's obviously still iteration on the back end in C).

VOWELS = set("aeiou")

def count_vowels(s: str) -> int:
    return len(VOWELS.intersection(s.lower()))

Examples:

In [6]: count_vowels("Eat")
Out[6]: 2

In [7]: count_vowels("sweEt")
Out[7]: 1

In [8]: count_vowels("hello")
Out[8]: 2

In [9]: count_vowels("aeiou")
Out[9]: 5

In [10]: count_vowels("aeiou"*10)
Out[10]: 5

In [11]: count_vowels("")
Out[11]: 0

In [12]: count_vowels("syzygy")
Out[12]: 0