问:
How to build a search engine box in web-development
I would like to make a search engine box where I can search country names.

About the User Interface, I want it to be like Google search engine box.

It activates when a user tries to type something, and it does not close by clicking the input typing box.

It only closes when the user clicks outside the input box or a recommendation keyword.

How can I build this type of search engine box?
If it is possible, can you please show me some of the codes as well? Thank you a lot.

Google search engine box

答:
Welp, you'll need an <input type="text /> for the search bar. Style it up and give it functionality in js.
I suggest making an array of countries or getting from the internet and for every interaction with the search bar, give our some results with jquery.


来源: stackexchange

问:
managing items in a List based off some conditions in C#
I have a couple of lists  List<OldData> oldItems = new List<OldData>(); and List<NewData> newItems = new List<NewData>();

What I am trying to achieve here is to avoid the possibility of some redundant data coming in hence to check with some conditions before values are added into the list.

First up in the oldItems  I will have some values stored and in the newItems list I will have a completely different set of values stored but it could always be the case that the newItems list may have some values that are already existing in the  oldItems list.

The two variables that are in use are a Name variable and a path variable which stores a certain path

So First I want to check if there are any values where the name in the old items List is equal to the name in the new Items List ,
if There is an Item I want to check if the respective Path variable of the corresponding items are same ,

if it is same I can simply keep that item the way it is in the OldItems list , if that happens to be different I will Remove that from the old Items List (and later use the item in the new Item List)

So all the above in a nut shell ,

I want to check for in the Old Items List where there is a Name Corresponding to it in the new Item List
If there is , I want to check if the corresponding values in the Path variable for the two items with the same name from the two List are the same or different

I have made a simple dummy application to demo this but really stuck on how i can implement the logic

any suggestion ?

```<code>class Program
{
    static void Main(string[] args)
    {

        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData1.Name = "Test02";
        oldData1.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        oldData1.Name = "Test05";
        oldData1.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        foreach (var item in oldItems)
        {
            //Check if there are any Names which are same from the new Item list
            //If if there is such an item check if the OriginalPath variable is the same iin both
            //If yes => Remove that particular item from the Old data List
            //If Not => Keep that Item in  the old data List
        }
    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}
</code>```

In this case since the value Test01 is common to both List It will check if the path variable values corresponding to both items are the same or not

答:
1) I would implement an interface with the shared properties

2) We make both the classes implement it (which is already done anyway)

3) We implement an EqualityComparer for the specific interface which will check only the properties we want from both the objects implementing our interface

That's an implementation example:

```<code>class Program
{
    static void Main(string[] args)
    {
        OldData oldData = new OldData
        {
            Name = "Pizza",
            OriginalPath = "Pozza"
        };

        NewData newData = new NewData
        {
            Name = "Pizza",
            OriginalPath = "Pozza"
        };

        var comparer = new CommonDataComparer();

        bool areEqual = comparer.Equals(oldData, newData);

        Console.WriteLine(areEqual);
    }
}

public interface ICommonData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

public class OldData : ICommonData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
    //Old other properties
}

public class NewData : ICommonData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
    //New other properties
}

public class CommonDataComparer : IEqualityComparer<ICommonData>
{
    public bool Equals([AllowNull] ICommonData x, [AllowNull] ICommonData y)
    {
        return ((x?.Name == y?.Name) && (x?.OriginalPath == y?.OriginalPath));
    }

    public int GetHashCode([DisallowNull] ICommonData obj)
    {
        return obj.Name.GetHashCode() + obj.OriginalPath.GetHashCode();
    }
}
</code>```

Output:

True

ContentLicense: CC BY-SA 4.0

Body:
I have a couple of lists  List<OldData> oldItems = new List<OldData>(); and List<NewData> newItems = new List<NewData>();

What I am trying to achieve here is to avoid the possibility of some redundant data coming in hence to check with some conditions before values are added into the list.

First up in the oldItems  I will have some values stored and in the newItems list I will have a completely different set of values stored but it could always be the case that the newItems list may have some values that are already existing in the  oldItems list.

The two variables that are in use are a Name variable and a path variable which stores a certain path

So First I want to check if there are any values where the name in the old items List is equal to the name in the new Items List ,
if There is an Item I want to check if the respective Path variable of the corresponding items are same ,

if it is same I can simply keep that item the way it is in the OldItems list , if that happens to be different I will Remove that from the old Items List (and later use the item in the new Item List)

So all the above in a nut shell ,

I want to check for in the Old Items List where there is a Name Corresponding to it in the new Item List
If there is , I want to check if the corresponding values in the Path variable for the two items with the same name from the two List are the same or different

I have made a simple dummy application to demo this but really stuck on how i can implement the logic

any suggestion ?

class Program
{
    static void Main(string[] args)
    {

        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData1.Name = "Test02";
        oldData1.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        oldData1.Name = "Test05";
        oldData1.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        foreach (var item in oldItems)
        {
            //Check if there are any Names which are same from the new Item list
            //If if there is such an item check if the OriginalPath variable is the same iin both
            //If yes => Remove that particular item from the Old data List
            //If Not => Keep that Item in  the old data List
        }
    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

In this case since the value Test01 is common to both List It will check if the path variable values corresponding to both items are the same or not

Body:
1) I would implement an interface with the shared properties

2) We make both the classes implement it (which is already done anyway)

3) We implement an EqualityComparer for the specific interface which will check only the properties we want from both the objects implementing our interface

That's an implementation example:

class Program
{
    static void Main(string[] args)
    {
        OldData oldData = new OldData
        {
            Name = "Pizza",
            OriginalPath = "Pozza"
        };

        NewData newData = new NewData
        {
            Name = "Pizza",
            OriginalPath = "Pozza"
        };

        var comparer = new CommonDataComparer();

        bool areEqual = comparer.Equals(oldData, newData);

        Console.WriteLine(areEqual);
    }
}

public interface ICommonData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

public class OldData : ICommonData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
    //Old other properties
}

public class NewData : ICommonData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
    //New other properties
}

public class CommonDataComparer : IEqualityComparer<ICommonData>
{
    public bool Equals([AllowNull] ICommonData x, [AllowNull] ICommonData y)
    {
        return ((x?.Name == y?.Name) && (x?.OriginalPath == y?.OriginalPath));
    }

    public int GetHashCode([DisallowNull] ICommonData obj)
    {
        return obj.Name.GetHashCode() + obj.OriginalPath.GetHashCode();
    }
}

Output:

True


问:
What is equivalent of DocumentClientException.RetryAfter in MongoDB C# driver?
We are using Azure CosmosDB with MongoDB API + MongoDB C# driver. Microsoft's office SDK works only with CosmosDB SQL API (DocumentDB) and has an built-in ability to retry write operations. For this it uses DocumentClientException.RetryAfter property as a delay. However with Mongo driver this is not possible. `It only returns error as:

```<code>Command insert failed: Message: {"Errors":["Request rate is large"]}.
</code>```

Currently we have put 1 second retry delay when an write exception occurs, however this is not very clean and causes fixed amount of delays per bulk write operations. It is not real time meaning sometimes we delay writing next batches of records longer than necessary.

How do we handle this?

答:
In CosmosDB, when you're using a V3.2 MongoDB endpoint, then no retry information is returned and you basically have guess and/or use some sort of exponential backoff. The exceptions you have to handle in this scenario include: MongoCommandException and MongoExecutionTimeoutException

In V3.6, MongoDB endpoint does return RetryAfterMs= information as part of either MongoBulkWriteException or MongoWriteException. Unfortunately, as far as I can tell, you have to extract this information from the error message as there is no property containing this value.
Note: This may be an issue in non-english systems as error messages could be translated.

Below is what I've implemented using Polly - both endpoint versions are supported and the V3.6 policy is backwards compatible with V3.2.

Obviously, you may wish to tweak some of the values based on your scenario.

```<code>    public static class Policies
    {
        public const int HttpThrottleErrorCode = 429;
        public const int HttpServiceIsUnavailable = 1;
        public const int HttpOperationExceededTimeLimit = 50;
        public const int RateLimitCode = 16500;
        public const string RetryAfterToken = "RetryAfterMs=";
        public const int MaxRetries = 10;
        public static readonly int RetryAfterTokenLength = RetryAfterToken.Length;

        private static readonly Random JitterSeed = new Random();

        public static readonly IAsyncPolicy NoPolicy = Policy.NoOpAsync();

        public static Func<int, TimeSpan> SleepDurationProviderWithJitter(double exponentialBackoffInSeconds, int maxBackoffTimeInSeconds) => retryAttempt
            => TimeSpan.FromSeconds(Math.Min(Math.Pow(exponentialBackoffInSeconds, retryAttempt), maxBackoffTimeInSeconds)) // exponential back-off: 2, 4, 8 etc
               + TimeSpan.FromMilliseconds(JitterSeed.Next(0, 1000)); // plus some jitter: up to 1 second

        public static readonly Func<int, TimeSpan> DefaultSleepDurationProviderWithJitter =
            SleepDurationProviderWithJitter(1.5, 23);

        public static readonly IAsyncPolicy MongoCommandExceptionPolicy = Policy
            .Handle<MongoCommandException>(e =>
            {
                if (e.Code != RateLimitCode || !(e.Result is BsonDocument bsonDocument))
                {
                    return false;
                }

                if (bsonDocument.TryGetValue("StatusCode", out var statusCode) && statusCode.IsInt32)
                {
                    switch (statusCode.AsInt32)
                    {
                        case HttpThrottleErrorCode:
                        case HttpServiceIsUnavailable:
                        case HttpOperationExceededTimeLimit:
                            return true;
                        default:
                            return false;
                    }
                }

                if (bsonDocument.TryGetValue("IsValid", out var isValid) && isValid.IsBoolean)
                {
                    return isValid.AsBoolean;
                }

                return true;
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy ExecutionTimeoutPolicy = Policy
            .Handle<MongoExecutionTimeoutException>(e =>
                e.Code == RateLimitCode || e.Code == HttpOperationExceededTimeLimit
            )
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy MongoWriteExceptionPolicy = Policy
            .Handle<MongoWriteException>(e =>
            {
                return e.WriteError?.Code == RateLimitCode
                       || (e.InnerException is MongoBulkWriteException bulkException &&
                           bulkException.WriteErrors.Any(error => error.Code == RateLimitCode));
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    if (!timeToWaitInMs.HasValue && e.InnerException != null)
                    {
                        timeToWaitInMs = ExtractTimeToWait(e.InnerException.Message);
                    }
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        public static readonly IAsyncPolicy MongoBulkWriteExceptionPolicy = Policy
            .Handle<MongoBulkWriteException>(e =>
            {
                return e.WriteErrors.Any(error => error.Code == RateLimitCode);
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        /// <summary>
        /// It doesn't seem like RetryAfterMs is a property value - so unfortunately, we have to extract it from a string... (crazy??!)
        /// </summary>
        private static TimeSpan? ExtractTimeToWait(string messageToParse)
        {
            var retryPos = messageToParse.IndexOf(RetryAfterToken, StringComparison.OrdinalIgnoreCase);
            if (retryPos >= 0)
            {
                retryPos += RetryAfterTokenLength;
                var endPos = messageToParse.IndexOf(',', retryPos);
                if (endPos > 0)
                {
                    var timeToWaitInMsString = messageToParse.Substring(retryPos, endPos - retryPos);
                    if (Int32.TryParse(timeToWaitInMsString, out int timeToWaitInMs))
                    {
                        return TimeSpan.FromMilliseconds(timeToWaitInMs)
                               + TimeSpan.FromMilliseconds(JitterSeed.Next(100, 1000));
                    }
                }
            }
            return default;
        }

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_2 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy);

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.6 or V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_6 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy, MongoWriteExceptionPolicy, MongoBulkWriteExceptionPolicy);
    }

    public static IAsyncPolicy DefaultPolicy { get; set; } = Policies.DefaultPolicyForMongo3_6;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are using Azure CosmosDB with MongoDB API + MongoDB C# driver. Microsoft's office SDK works only with CosmosDB SQL API (DocumentDB) and has an built-in ability to retry write operations. For this it uses DocumentClientException.RetryAfter property as a delay. However with Mongo driver this is not possible. `It only returns error as:

Command insert failed: Message: {"Errors":["Request rate is large"]}.

Currently we have put 1 second retry delay when an write exception occurs, however this is not very clean and causes fixed amount of delays per bulk write operations. It is not real time meaning sometimes we delay writing next batches of records longer than necessary.

How do we handle this?

Body:
In CosmosDB, when you're using a V3.2 MongoDB endpoint, then no retry information is returned and you basically have guess and/or use some sort of exponential backoff. The exceptions you have to handle in this scenario include: MongoCommandException and MongoExecutionTimeoutException

In V3.6, MongoDB endpoint does return RetryAfterMs= information as part of either MongoBulkWriteException or MongoWriteException. Unfortunately, as far as I can tell, you have to extract this information from the error message as there is no property containing this value.
Note: This may be an issue in non-english systems as error messages could be translated.

Below is what I've implemented using Polly - both endpoint versions are supported and the V3.6 policy is backwards compatible with V3.2.

Obviously, you may wish to tweak some of the values based on your scenario.

    public static class Policies
    {
        public const int HttpThrottleErrorCode = 429;
        public const int HttpServiceIsUnavailable = 1;
        public const int HttpOperationExceededTimeLimit = 50;
        public const int RateLimitCode = 16500;
        public const string RetryAfterToken = "RetryAfterMs=";
        public const int MaxRetries = 10;
        public static readonly int RetryAfterTokenLength = RetryAfterToken.Length;

        private static readonly Random JitterSeed = new Random();

        public static readonly IAsyncPolicy NoPolicy = Policy.NoOpAsync();

        public static Func<int, TimeSpan> SleepDurationProviderWithJitter(double exponentialBackoffInSeconds, int maxBackoffTimeInSeconds) => retryAttempt
            => TimeSpan.FromSeconds(Math.Min(Math.Pow(exponentialBackoffInSeconds, retryAttempt), maxBackoffTimeInSeconds)) // exponential back-off: 2, 4, 8 etc
               + TimeSpan.FromMilliseconds(JitterSeed.Next(0, 1000)); // plus some jitter: up to 1 second

        public static readonly Func<int, TimeSpan> DefaultSleepDurationProviderWithJitter =
            SleepDurationProviderWithJitter(1.5, 23);

        public static readonly IAsyncPolicy MongoCommandExceptionPolicy = Policy
            .Handle<MongoCommandException>(e =>
            {
                if (e.Code != RateLimitCode || !(e.Result is BsonDocument bsonDocument))
                {
                    return false;
                }

                if (bsonDocument.TryGetValue("StatusCode", out var statusCode) && statusCode.IsInt32)
                {
                    switch (statusCode.AsInt32)
                    {
                        case HttpThrottleErrorCode:
                        case HttpServiceIsUnavailable:
                        case HttpOperationExceededTimeLimit:
                            return true;
                        default:
                            return false;
                    }
                }

                if (bsonDocument.TryGetValue("IsValid", out var isValid) && isValid.IsBoolean)
                {
                    return isValid.AsBoolean;
                }

                return true;
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy ExecutionTimeoutPolicy = Policy
            .Handle<MongoExecutionTimeoutException>(e =>
                e.Code == RateLimitCode || e.Code == HttpOperationExceededTimeLimit
            )
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy MongoWriteExceptionPolicy = Policy
            .Handle<MongoWriteException>(e =>
            {
                return e.WriteError?.Code == RateLimitCode
                       || (e.InnerException is MongoBulkWriteException bulkException &&
                           bulkException.WriteErrors.Any(error => error.Code == RateLimitCode));
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    if (!timeToWaitInMs.HasValue && e.InnerException != null)
                    {
                        timeToWaitInMs = ExtractTimeToWait(e.InnerException.Message);
                    }
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        public static readonly IAsyncPolicy MongoBulkWriteExceptionPolicy = Policy
            .Handle<MongoBulkWriteException>(e =>
            {
                return e.WriteErrors.Any(error => error.Code == RateLimitCode);
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        /// <summary>
        /// It doesn't seem like RetryAfterMs is a property value - so unfortunately, we have to extract it from a string... (crazy??!)
        /// </summary>
        private static TimeSpan? ExtractTimeToWait(string messageToParse)
        {
            var retryPos = messageToParse.IndexOf(RetryAfterToken, StringComparison.OrdinalIgnoreCase);
            if (retryPos >= 0)
            {
                retryPos += RetryAfterTokenLength;
                var endPos = messageToParse.IndexOf(',', retryPos);
                if (endPos > 0)
                {
                    var timeToWaitInMsString = messageToParse.Substring(retryPos, endPos - retryPos);
                    if (Int32.TryParse(timeToWaitInMsString, out int timeToWaitInMs))
                    {
                        return TimeSpan.FromMilliseconds(timeToWaitInMs)
                               + TimeSpan.FromMilliseconds(JitterSeed.Next(100, 1000));
                    }
                }
            }
            return default;
        }

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_2 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy);

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.6 or V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_6 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy, MongoWriteExceptionPolicy, MongoBulkWriteExceptionPolicy);
    }

    public static IAsyncPolicy DefaultPolicy { get; set; } = Policies.DefaultPolicyForMongo3_6;


问:
When using CSS Variables (CSS Custom Properties) why is the setting syntax and the getting syntax different?
When using CSS Variables (CSS Custom Properties) why is the setting syntax and the getting syntax different?

If I wish to set a value for --my-custom-width, I will use:

```<code>:root {
  --my-custom-width: 120px;
}
</code>```

And if I wish to get a value for --my-custom-width, I will use a var() function to retrieve the same value:

```<code>.my-div {
  width: var(--my-custom-width);
}
</code>```

Why do we not simply write:

```<code>.my-div {
  width: --my-custom-width;
}
</code>```

答:
Having been using CSS Custom Properties since late 2017, I've finally understood properly what they really are and why the var() function is necessary...

They are not (as they so often appear to be) variables intended to directly represent CSS values.

CSS Custom Properties are exactly what they say they are - they are new CSS properties which have not (yet) been assigned values.

In CSS, an example of something which really does approximate a variable representing a value is currentColor.

We see currentColor representing a value, here:

```<code>.my-div {
  border: 1px dashed currentColor;
}
</code>```

But CSS Custom Properties are not CSS variables which stand in for values like currentColor, .

Instead, CSS Custom Properties are newly invented, named, null-value-properties...

... and those newly-invented, named, null-value-properties are completely re-usable. Just like width, height, color etc. they may have values set and reset in different contexts.

E.g.

```<code>/* My custom property is --my-custom-width but I want this
   property to hold different values in different contexts */

.left-two-thirds-of-page {
  --my-custom-width: 120px;
}

.right-third-of-page {
  --my-custom-width: 60px;
}

.my-div {
  width: var(--my-custom-width);
}
</code>```

That's why the var() function is necessary - it's not delivering "the custom property" - it's extracting the value that custom property is currently holding and then delivering that value.

Further Thoughts:

In hindsight, I wonder if the whole name-value relationship wouldn't have been a little clearer if CSS Custom Properties had been called:

```<code>CSS Custom Property Names
</code>```

and the corresponding function had been called:

```<code>value()
</code>```

so the syntax would have been written and read out as:

```<code>value(--my-custom-property-name)
</code>```

By extension we could use the value() function (or var() function) not just on custom properties but on any property.

For instance:

```<code>width: value(height);
</code>```

Body:
When using CSS Variables (CSS Custom Properties) why is the setting syntax and the getting syntax different?

If I wish to set a value for --my-custom-width, I will use:

:root {
  --my-custom-width: 120px;
}

And if I wish to get a value for --my-custom-width, I will use a var() function to retrieve the same value:

.my-div {
  width: var(--my-custom-width);
}

Why do we not simply write:

.my-div {
  width: --my-custom-width;
}

Body:
Having been using CSS Custom Properties since late 2017, I've finally understood properly what they really are and why the var() function is necessary...

They are not (as they so often appear to be) variables intended to directly represent CSS values.

CSS Custom Properties are exactly what they say they are - they are new CSS properties which have not (yet) been assigned values.

In CSS, an example of something which really does approximate a variable representing a value is currentColor.

We see currentColor representing a value, here:

.my-div {
  border: 1px dashed currentColor;
}

But CSS Custom Properties are not CSS variables which stand in for values like currentColor, .

Instead, CSS Custom Properties are newly invented, named, null-value-properties...

... and those newly-invented, named, null-value-properties are completely re-usable. Just like width, height, color etc. they may have values set and reset in different contexts.

E.g.

/* My custom property is --my-custom-width but I want this
   property to hold different values in different contexts */

.left-two-thirds-of-page {
  --my-custom-width: 120px;
}

.right-third-of-page {
  --my-custom-width: 60px;
}

.my-div {
  width: var(--my-custom-width);
}

That's why the var() function is necessary - it's not delivering "the custom property" - it's extracting the value that custom property is currently holding and then delivering that value.

Further Thoughts:

In hindsight, I wonder if the whole name-value relationship wouldn't have been a little clearer if CSS Custom Properties had been called:

CSS Custom Property Names

and the corresponding function had been called:

value()

so the syntax would have been written and read out as:

value(--my-custom-property-name)

By extension we could use the value() function (or var() function) not just on custom properties but on any property.

For instance:

width: value(height);


问:
How do I resolve Activity Not Found Exception
In my android app, I've added an activity MainActivity in the manifest file, on navigating to that activity using an inten I get activity not found error asking if I've added it to manifest

here is my manifest activity

```<code>        <activity
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:icon="@mipmap/ic_launcher"
            android:rotationAnimation="seamless"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat"
            tools:targetApi="O">

             <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.OPENABLEk" />
             </intent-filter>

<!--            Register as a system camera app-->
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
                <action android:name="android.media.action.VIDEO_CAMERA" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <!-- App links for http/s -->
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="example.android.com" />
                <data android:pathPattern="/camerax" />
            </intent-filter>

            <!-- Declare notch support -->
            <meta-data
                android:name="android.notch_support"
                android:value="true" />
        </activity>
</code>```

here is the log

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.virtusync.scanningtool, PID: 28538
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
        at com.android.example.cameraxbasic.SelectOperation$1.onClick(SelectOperation.java:36)
        at android.view.View.performClick(View.java:7044)
        at android.view.View.performClickInternal(View.java:7017)
        at android.view.View.access$3200(View.java:784)
        at android.view.View$PerformClick.run(View.java:26596)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

</code>```

I've done this
How to fix "android.content.ActivityNotFoundException" android-studio 2.3.3
no solution yet

答:
Did you rename your activity?
The Error Message says "MainActivityKt" not found, but the Activity in your Manifest File is called "MainActivity".

Rename the activity in your Manifest or the Java class.

Body:
In my android app, I've added an activity MainActivity in the manifest file, on navigating to that activity using an inten I get activity not found error asking if I've added it to manifest

here is my manifest activity

        <activity
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:icon="@mipmap/ic_launcher"
            android:rotationAnimation="seamless"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat"
            tools:targetApi="O">

             <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.OPENABLEk" />
             </intent-filter>

            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
                <action android:name="android.media.action.VIDEO_CAMERA" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="example.android.com" />
                <data android:pathPattern="/camerax" />
            </intent-filter>

            <meta-data
                android:name="android.notch_support"
                android:value="true" />
        </activity>

here is the log

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.virtusync.scanningtool, PID: 28538
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
        at com.android.example.cameraxbasic.SelectOperation$1.onClick(SelectOperation.java:36)
        at android.view.View.performClick(View.java:7044)
        at android.view.View.performClickInternal(View.java:7017)
        at android.view.View.access$3200(View.java:784)
        at android.view.View$PerformClick.run(View.java:26596)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

I've done this
How to fix "android.content.ActivityNotFoundException" android-studio 2.3.3
no solution yet


问:
Mathjax won't reload when using mithril mount function
I am using Mithril and am dynamically mounting some content.  the first time the page loads everything works fine.  Once I click a button, which causes one thing to unmount and another to mount, the Mathjax won't render again. I have tried calling the MathJax.Hub.Queue(["Typeset",MathJax.Hub]); function on element and page load, but it still does not work.  The console indicates that MathJax.Hub is undefined after the remount.  MathJax itself is being loaded synchronously.

What can I do?

答: Your error message suggests that you may be using MathJax version 3 rather than version 2.  The MathJax API has changed significantly with version 3, and MathJax.Hub is no longer part of version 3.  The replacement you are looking for is probably MathJax.typesetPromise().  See the MathJax documentation for typesetting and converting math for more details.


问:
The package javax.xml.namespace is accessible from more than one module
My environment:

Java 11

Spring Boot

Gradle

Not sure how to fix this error:

The package javax.xml.namespace is accessible from more than one module: <unnamed>, java.xml
```

答:
As many other questions and answers related this topic suggests, the error is related to a duplicity with java.xml import. By default, on Java 11, java.xml is part of the JDK libraries, and is added in the modulepath.

Check the dependencies of your graddle, at least one of then is also adding a transitive dependence to java.xml but in the classpath (unnamed module),thus it is present twice.

Locate the dependency that is adding it, and try adding something similar to this on you gradle (in my case the duplicity was due to Apache Tika library):

```<code>compile ('org.apache.tika:tika-parsers:1.22') {
    exclude (group: 'xml-apis')
}
</code>```

Body:
As many other questions and answers related this topic suggests, the error is related to a duplicity with java.xml import. By default, on Java 11, java.xml is part of the JDK libraries, and is added in the modulepath.

Check the dependencies of your graddle, at least one of then is also adding a transitive dependence to java.xml but in the classpath (unnamed module),thus it is present twice.

Locate the dependency that is adding it, and try adding something similar to this on you gradle (in my case the duplicity was due to Apache Tika library):

compile ('org.apache.tika:tika-parsers:1.22') {
    exclude (group: 'xml-apis')
}


问:
How to pass file name as column in Spark
I need to pass array of Hadoop file path to spark.read

```<code>status= Array(org.apache.hadoop.fs.FileStatus)
</code>```

I tried:

```<code>val s = spark.read.format("json").load(status: _*)

</code>```

Error:

```<code>
<console>:32: error: overloaded method value load with alternatives:

  (paths: String*)org.apache.spark.sql.DataFrame <and>

  (path: String)org.apache.spark.sql.DataFrame

cannot be applied to (org.apache.hadoop.fs.FileStatus)

       val s = spark.read.format("json").load(status: _*)

</code>```

How to pass file name as column in Spark?

答:
You have to get file paths from the array of FileStatus objects first.

This should work fine:

```<code>val files = status.map(_.getPath().toString)

val df = spark.read.format("json").load(files: _*)
</code>```

Body:
I need to pass array of Hadoop file path to spark.read

status= Array(org.apache.hadoop.fs.FileStatus)

I tried:

val s = spark.read.format("json").load(status: _*)

Error:

<console>:32: error: overloaded method value load with alternatives:

  (paths: String*)org.apache.spark.sql.DataFrame <and>

  (path: String)org.apache.spark.sql.DataFrame

cannot be applied to (org.apache.hadoop.fs.FileStatus)

       val s = spark.read.format("json").load(status: _*)

How to pass file name as column in Spark?

Body:
You have to get file paths from the array of FileStatus objects first.

This should work fine:

val files = status.map(_.getPath().toString)

val df = spark.read.format("json").load(files: _*)


问:
How to output all lines to a given writer and return the number of bytes
How can I output to a given writer all the rows in the list that consist only of Latin letters or numbers and return the number of successfully written bytes before the first exception using a lambda expression?

My code:

```<code>public int writeAllCountingBytesTransferred(Writer writer, List<String> list) {
    return list.stream().filter(x -> x.matches("^[a-zA-Z0-9]+$") ).forEach(x-> {
        try {
            writer.write(x);
            how do I count bytes?
        } catch (IOException e) {
            how do I return bytes?

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

答:
I would map to an IntStream of the string lengths and sum() it:

```<code>return list.stream()
    .filter(x -> x.matches("^[a-zA-Z0-9]+$"))
    .mapToInt(x-> {
      try {
        writer.write(x);
        return x.length();
      } catch (IOException e) {
        return 0;
      }
    })
    .sum();
</code>```

Note that when the strings are all letters and digits the char length and byte length are the same.

Body:
How can I output to a given writer all the rows in the list that consist only of Latin letters or numbers and return the number of successfully written bytes before the first exception using a lambda expression?

My code:

public int writeAllCountingBytesTransferred(Writer writer, List<String> list) {
    return list.stream().filter(x -> x.matches("^[a-zA-Z0-9]+$") ).forEach(x-> {
        try {
            writer.write(x);
            how do I count bytes?
        } catch (IOException e) {
            how do I return bytes?

        }
    });
}

Body:
I would map to an IntStream of the string lengths and sum() it:

return list.stream()
    .filter(x -> x.matches("^[a-zA-Z0-9]+$"))
    .mapToInt(x-> {
      try {
        writer.write(x);
        return x.length();
      } catch (IOException e) {
        return 0;
      }
    })
    .sum();

Note that when the strings are all letters and digits the char length and byte length are the same.


问:
Gorilla mux remove or replace existing routes
I'm learning Go and came across the gorilla/mux router. I wanted to have dynamic routes in a text file such as:

/user/1

/post/1

I wrote the following code for this purpose :

```<code>func (s *Server) RegRoutes(routes []Route) {
    for _, r := range routes {
        func(route Route) {
            s.Router.HandleFunc(route.Path, func(w http.ResponseWriter, r *http.Request) {
                w.Header().Add("Content-Type", "application/json")
                s.sendJson(w, route) // send response to client
            }).Methods(route.Method)
        }(r)
    }
}
</code>```

and everything is working fine. But I want to edit the text file and add some more fields or edit the existing ones without rebuild the project or restart the server. I found this but I couldn't understand what is it and I don't know how to use it.

Is there anyway to modify the existing routes or add more routes during the run-time?

Edit:

I added this:

```<code>s.Router.HandleFunc("/reload", func(w http.ResponseWriter, r *http.Request) {

        s.mu.Lock()
        s.Router = mux.NewRouter()
        s.mu.Unlock()

        // load text file and register new routes here
        ....

        s.Router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
            tpl, err1 := route.GetPathTemplate()
            met, err2 := route.GetMethods()
            fmt.Println(tpl, err1, met, err2)
            return nil
        })
        fmt.Fprintf(w, "RELOAD")
    })
</code>```

When I print the routes after registering the new routes and replacing the Router, they are registered but when I browse the route in browser it gives me 404 error.

答:
If I understand what you are trying to achieve, it will look something like this:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
)

var router = mux.NewRouter()
func handler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("bla"))
}

func reloadHandler(w http.ResponseWriter, r *http.Request) {
    router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
        t, err := route.GetPathTemplate()
        if err != nil {
            return err
        }
        fmt.Println(t)
        if t == "/" {
            route.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
                writer.Write([]byte("akjbsdkabdjkbaksdj"))
            })
        }
        return nil
    })
}

func main() {

    router.HandleFunc("/", handler)
    router.HandleFunc("/reload", reloadHandler)

    http.ListenAndServe("localhost:8080", router)
}

```

The router declaration goes outside main function and it can be accessed by the reload handler to add another route.

and the path walk you can check if it is the path you want to change, and then change it.

Body:
I'm learning Go and came across the gorilla/mux router. I wanted to have dynamic routes in a text file such as:

/user/1

/post/1

I wrote the following code for this purpose :

func (s *Server) RegRoutes(routes []Route) {
    for _, r := range routes {
        func(route Route) {
            s.Router.HandleFunc(route.Path, func(w http.ResponseWriter, r *http.Request) {
                w.Header().Add("Content-Type", "application/json")
                s.sendJson(w, route) // send response to client
            }).Methods(route.Method)
        }(r)
    }
}

and everything is working fine. But I want to edit the text file and add some more fields or edit the existing ones without rebuild the project or restart the server. I found this but I couldn't understand what is it and I don't know how to use it.

Is there anyway to modify the existing routes or add more routes during the run-time?

Edit:

I added this:

s.Router.HandleFunc("/reload", func(w http.ResponseWriter, r *http.Request) {

        s.mu.Lock()
        s.Router = mux.NewRouter()
        s.mu.Unlock()

        // load text file and register new routes here
        ....

        s.Router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
            tpl, err1 := route.GetPathTemplate()
            met, err2 := route.GetMethods()
            fmt.Println(tpl, err1, met, err2)
            return nil
        })
        fmt.Fprintf(w, "RELOAD")
    })

When I print the routes after registering the new routes and replacing the Router, they are registered but when I browse the route in browser it gives me 404 error.

Body:
If I understand what you are trying to achieve, it will look something like this:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
)

var router = mux.NewRouter()
func handler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("bla"))
}

func reloadHandler(w http.ResponseWriter, r *http.Request) {
    router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
        t, err := route.GetPathTemplate()
        if err != nil {
            return err
        }
        fmt.Println(t)
        if t == "/" {
            route.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
                writer.Write([]byte("akjbsdkabdjkbaksdj"))
            })
        }
        return nil
    })
}

func main() {

    router.HandleFunc("/", handler)
    router.HandleFunc("/reload", reloadHandler)

    http.ListenAndServe("localhost:8080", router)
}

The router declaration goes outside main function and it can be accessed by the reload handler to add another route.

and the path walk you can check if it is the path you want to change, and then change it.


问:
Is possible to achieve a "pixel perfect" positioning with React Native apps?
I have an app using Ionic Framework with dozens of custom images on top of each other (layered),
SVG text elements(with custom paths) and a few javascript plugins.

I thought of porting to React Native, but couldn't get a proper place to ask other than here..

Any React developer can give some directions, if a port is possible?

答:
Yes, you can Port your Ionic Application to React Native with Pixel Perfect UI. For a specific Platform for IOS and Android, You can also write your code. You can start with React Native latest 0.61 React Native Documentation. And for Specific positioning for your SVG images, you can find several npm modules.
This is a great idea from moving your ionic App to React Native, It will give your App best performance as well as several npm packages are also available which makes its development fast and efficient.</p>


问:
Django All-Auth django.contrib.auth.backends.ModelBackend invalid syntax
I am fairly new to Django so I have been following tutorials and guides to learn as I go along. I am currently attempting to do a E-commerce Django project following a youtube tutorial by freeCodeCamp.

In the beginning you need to install Django-AllAuth which I have done.

The issue I am currently having is when you need to migrate the installed apps it throws me a 'Invalid Syntax Error' on the 'django.contrib.auth.backends.ModelBackend' in the Authentication_Backends section in settings.

My settings.py

```<code>import os

ENVIRONMENT = os.getenv('ENVIRONMENT', 'development')

DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj'
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'core'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
]

ROOT_URLCONF = 'ecommerce.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, 'db.sqlite3')
    }
}

if ENVIRONMENT == 'production':
    DEBUG = False
    SECRET_KEY = os.getenv('SECRET_KEY')
    SESSION_COOKIE_SECURE = True
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_SECONDS = 31536000
    SECURE_REDIRECT_EXEMPT = []
    SECURE_SSL_REDIRECT = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Auth

AUTHENTICATION_BACKENDS = (
    ...
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
    ...
)
SITE_ID = 1

</code>```

The error I am getting

```<code>PS G:\Git\Django\ecommerce> python manage.py migrate sites
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\core\management\__init__.py", line 325, in execute
    settings.INSTALLED_APPS
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__

    self._setup(name)
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\conf\__init__.py", line 66, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\conf\__init__.py", line 157, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 674, in exec_module
  File "<frozen importlib._bootstrap_external>", line 781, in get_code
  File "<frozen importlib._bootstrap_external>", line 741, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "G:\Git\Django\ecommerce\ecommerce\settings.py", line 90
    'django.contrib.auth.backends.ModelBackend',
                                              ^
SyntaxError: invalid syntax
</code>```

Any help will be greatly appreciated.

答:
I manage to fix the issue by removing the '...'</p>

```<code>AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)
</code>```

Body:
I am fairly new to Django so I have been following tutorials and guides to learn as I go along. I am currently attempting to do a E-commerce Django project following a youtube tutorial by freeCodeCamp.

In the beginning you need to install Django-AllAuth which I have done.

The issue I am currently having is when you need to migrate the installed apps it throws me a 'Invalid Syntax Error' on the 'django.contrib.auth.backends.ModelBackend' in the Authentication_Backends section in settings.

My settings.py

import os

ENVIRONMENT = os.getenv('ENVIRONMENT', 'development')

DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj'
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'core'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
]

ROOT_URLCONF = 'ecommerce.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, 'db.sqlite3')
    }
}

if ENVIRONMENT == 'production':
    DEBUG = False
    SECRET_KEY = os.getenv('SECRET_KEY')
    SESSION_COOKIE_SECURE = True
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_SECONDS = 31536000
    SECURE_REDIRECT_EXEMPT = []
    SECURE_SSL_REDIRECT = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Auth

AUTHENTICATION_BACKENDS = (
    ...
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
    ...
)
SITE_ID = 1

The error I am getting

PS G:\Git\Django\ecommerce> python manage.py migrate sites
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\core\management\__init__.py", line 325, in execute
    settings.INSTALLED_APPS
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__

    self._setup(name)
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\conf\__init__.py", line 66, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\dylan\Anaconda3\envs\djangoenv\lib\site-packages\django\conf\__init__.py", line 157, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 674, in exec_module
  File "<frozen importlib._bootstrap_external>", line 781, in get_code
  File "<frozen importlib._bootstrap_external>", line 741, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "G:\Git\Django\ecommerce\ecommerce\settings.py", line 90
    'django.contrib.auth.backends.ModelBackend',
                                              ^
SyntaxError: invalid syntax

Any help will be greatly appreciated.

Body:
I manage to fix the issue by removing the '...'

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)


问:
How I can understand from which URL the request came to the controller?
I tried to watch,

```<code>request.path_parameters
</code>```

but its not bring any result. I would be grateful for any advice

答:
request.referer

Sorry for the carelessness, I hope someone comes in handy

Body:
I tried to watch,

request.path_parameters

but its not bring any result. I would be grateful for any advice


问:
Sorting within specified range and loop until done - VBA Excel Marcro
It's me again. I've been trying different alternatives to sort the rows based on Col D per collection.

This is the closest one, yet there are 2 bugs found.

1- Loop and not able to exit when it reaches the last used rows.
It keeps sorting until I press  to force quitting
2- It's unable to sort where there is only one SKUs per collection
It sort the next collection as well. Sometimes 3 collections sorted.
e.g. Before Run - Row 9, 29, 32, 35, 45....

Here is my code. What's wrong with my code?

```<code>Sub SortingCollectionOnColD
With ActiveSheet.Range("A:A")
    Set FindSubtotal = .Find("Subtotal", After:=.Range("A1"), LookIn:=xlValues)
        If Not FindSubtotal Is Nothing Then
            firstOne = FindSubtotal.Address
            Do
                With FindSubtotal
                        Range("A" & FindSubtotal.Row - 1).Select
                        Set SortRange = Range(Selection, Selection.End(xlUp)).EntireRow
                        ActiveSheet.Sort.SortFields.Clear
                            ActiveSheet.Sort.SortFields.Add Key:=Range("C" & FindSubtotal.Row) _
                                , SortOn:=xlSortOnValues, Order:=xlAscending
                            With ActiveSheet.Sort
                                .SetRange SortRange
                                .Header = xlNo
                                .Orientation = xlTopToBottom
                                .Apply
                            End With
                End With
                Set FindSubtotal = .FindNext(FindSubtotal)
            Loop While Not FindSubtotal Is Nothing And FindSubtotal.Address <> firstOne
        End If
End With End Sub
</code>```

Before the run

Expected Result

After the run. highlighted the major failures

答:
Please test the next code, please. I could not reproduce your sheet and I changed the reference to sheet instead of A:A range, where it looks logic to me, but not knowing very well what you wanted to do, it would not be impossible to not return what exactly you need. Please let me know if/how it fits your need.

```<code>Sub LoopSubtotal()
  Dim FindSubtotal As Range, sh As Worksheet, firstOne As String
  Dim SortRange As Range
   Set sh = ActiveSheet
   With sh.Range("A:A")
    Set FindSubtotal = .Find("Subtotal", After:=.Range("A1"), LookIn:=xlValues)
    If Not FindSubtotal Is Nothing Then
            firstOne = FindSubtotal.Address
            Do
                sh.Range("A" & FindSubtotal.row - 1).Select
                Set SortRange = Range(Selection, Selection.End(xlUp)).EntireRow
                sh.Sort.SortFields.Clear
                    sh.Sort.SortFields.Add Key:=sh.Range("C" & FindSubtotal.row) _
                        , SortOn:=xlSortOnValues, Order:=xlAscending
                    With sh.Sort
                        .SetRange SortRange
                        .Header = xlNo
                        .Orientation = xlTopToBottom
                        .Apply
                    End With
                    Set FindSubtotal = .FindNext(FindSubtotal): Debug.Print FindSubtotal.Address
            Loop While Not FindSubtotal Is Nothing And FindSubtotal.Address <> firstOne
        End If
   End With
End Sub
</code>```

Try, please, running it line by line, pressing F8 and see what it does.

Body:
It's me again. I've been trying different alternatives to sort the rows based on Col D per collection.

This is the closest one, yet there are 2 bugs found.

1- Loop and not able to exit when it reaches the last used rows.
It keeps sorting until I press  to force quitting
2- It's unable to sort where there is only one SKUs per collection
It sort the next collection as well. Sometimes 3 collections sorted.
e.g. Before Run - Row 9, 29, 32, 35, 45....

Here is my code. What's wrong with my code?

Sub SortingCollectionOnColD
With ActiveSheet.Range("A:A")
    Set FindSubtotal = .Find("Subtotal", After:=.Range("A1"), LookIn:=xlValues)
        If Not FindSubtotal Is Nothing Then
            firstOne = FindSubtotal.Address
            Do
                With FindSubtotal
                        Range("A" & FindSubtotal.Row - 1).Select
                        Set SortRange = Range(Selection, Selection.End(xlUp)).EntireRow
                        ActiveSheet.Sort.SortFields.Clear
                            ActiveSheet.Sort.SortFields.Add Key:=Range("C" & FindSubtotal.Row) _
                                , SortOn:=xlSortOnValues, Order:=xlAscending
                            With ActiveSheet.Sort
                                .SetRange SortRange
                                .Header = xlNo
                                .Orientation = xlTopToBottom
                                .Apply
                            End With
                End With
                Set FindSubtotal = .FindNext(FindSubtotal)
            Loop While Not FindSubtotal Is Nothing And FindSubtotal.Address <> firstOne
        End If
End With End Sub

Before the run

Expected Result

After the run. highlighted the major failures

Body:
Please test the next code, please. I could not reproduce your sheet and I changed the reference to sheet instead of A:A range, where it looks logic to me, but not knowing very well what you wanted to do, it would not be impossible to not return what exactly you need. Please let me know if/how it fits your need.

Sub LoopSubtotal()
  Dim FindSubtotal As Range, sh As Worksheet, firstOne As String
  Dim SortRange As Range
   Set sh = ActiveSheet
   With sh.Range("A:A")
    Set FindSubtotal = .Find("Subtotal", After:=.Range("A1"), LookIn:=xlValues)
    If Not FindSubtotal Is Nothing Then
            firstOne = FindSubtotal.Address
            Do
                sh.Range("A" & FindSubtotal.row - 1).Select
                Set SortRange = Range(Selection, Selection.End(xlUp)).EntireRow
                sh.Sort.SortFields.Clear
                    sh.Sort.SortFields.Add Key:=sh.Range("C" & FindSubtotal.row) _
                        , SortOn:=xlSortOnValues, Order:=xlAscending
                    With sh.Sort
                        .SetRange SortRange
                        .Header = xlNo
                        .Orientation = xlTopToBottom
                        .Apply
                    End With
                    Set FindSubtotal = .FindNext(FindSubtotal): Debug.Print FindSubtotal.Address
            Loop While Not FindSubtotal Is Nothing And FindSubtotal.Address <> firstOne
        End If
   End With
End Sub

Try, please, running it line by line, pressing F8 and see what it does.


问:
Override default_manager of third party app (Django)
I am using django-address module (https://pypi.org/project/django-address/) in my project. Now I want to add get_by_natural_key method on the default manager of State model of django-address module.

Before Django 1.10 I was able to do it using this code

```<code>class CustomManager(models.Manager):
    def get_by_natural_key(self, state_name, country):
        country = Country.objects.get_or_create(name=country)[0]
        print(country)
        return State.objects.get_or_create(name=state_name, country=country)[0]

State.add_to_class('objects', CustomManager())
State.add_to_class('_default_manager', CustomManager())
</code>```

But from Django1.10, _default_manager is read-only and I am not sure how to add 'get_by_natural_key' method on default manager of model

答:
I would not recommend to override something that Django does not want you to override but if you still want to do it, you can override default_manager in Meta directly.

```<code>setattr(State._meta, 'default_manager', CustomManager())
</code>```

Body:
I am using django-address module (https://pypi.org/project/django-address/) in my project. Now I want to add get_by_natural_key method on the default manager of State model of django-address module.

Before Django 1.10 I was able to do it using this code

class CustomManager(models.Manager):
    def get_by_natural_key(self, state_name, country):
        country = Country.objects.get_or_create(name=country)[0]
        print(country)
        return State.objects.get_or_create(name=state_name, country=country)[0]

State.add_to_class('objects', CustomManager())
State.add_to_class('_default_manager', CustomManager())

But from Django1.10, _default_manager is read-only and I am not sure how to add 'get_by_natural_key' method on default manager of model

Body:
I would not recommend to override something that Django does not want you to override but if you still want to do it, you can override default_manager in Meta directly.

setattr(State._meta, 'default_manager', CustomManager())


问:
Multiple user authentication for Docker Private Registry running inside Kubernetes
I'm running a docker private registry inside a kubernetes cluster using the standard registry:2 image. The image has basic functionality to provide user authentication using the Apache htpasswd utility.
In my case multiple users need to access the repository and therefore need to setup username passwords for multiple different users. What would be the best approach to implement this.

I got the single user htpsswd based authentication working, but does not seem to find a way to enable auth for multiple users i.e. having proper access control.

The registry is SSL enabled.(TLS at the ingress level)

答:
There are multiple ways this could be done. First of all its possible to have multiple users in the htpasswd file. It was not working with docker becasue docker required the passwords to be hashed using bcrypt algorithm.

Use the -B flag while creating the htpasswd file.

```<code>sudo htpasswd -c -B /etc/apache2/.htpasswd <username1>
</code>```

Another way this could be done, is using nginx authentication annotations.

nginx.ingress.kubernetes.io/auth-url: "url to auth service"

If the service return 200, nginx forwards the request or else returns authentication error response. With this you could have a lot of custom logic as you create and manage the authentication server.

Body:
There are multiple ways this could be done. First of all its possible to have multiple users in the htpasswd file. It was not working with docker becasue docker required the passwords to be hashed using bcrypt algorithm.

Use the -B flag while creating the htpasswd file.

sudo htpasswd -c -B /etc/apache2/.htpasswd <username1>

Another way this could be done, is using nginx authentication annotations.

nginx.ingress.kubernetes.io/auth-url: "url to auth service"

If the service return 200, nginx forwards the request or else returns authentication error response. With this you could have a lot of custom logic as you create and manage the authentication server.


问:
Valgrind report an error in Rcpp function in HistDAWass package
I checked my package (HistDAWass 1.0.3) on Windows+RStudio and it was OK.
I received a report from CRAN with this message:

```<code> > ### Name: WH_adaptive.kmeans
 > ### Title: K-means of a dataset of histogram-valued data using adaptive
 > ###   Wasserstein distances
 > ### Aliases: WH_adaptive.kmeans
 >
 > ### ** Examples
 >
 > results=WH_adaptive.kmeans(x = BLOOD,k = 2, rep = 10,simplify =
TRUE,qua = 10,
standardize = TRUE)
==27368== Conditional jump or move depends on uninitialised value(s)
==27368==    at 0x4D6B2E: bcEval (svn/R-devel/src/main/eval.c:6517)
==27368==    by 0x4E8777: Rf_eval (svn/R-devel/src/main/eval.c:688)
==27368==    by 0x4EA336: R_execClosure (svn/R-devel/src/main/eval.c:1853)
==27368==    by 0x4EB113: Rf_applyClosure (svn/R-devel/src/main/eval.c:1779)
==27368==    by 0x4E8943: Rf_eval (svn/R-devel/src/main/eval.c:811)
==27368==    by 0x4ED2E1: do_set (svn/R-devel/src/main/eval.c:2920)
==27368==    by 0x4E8BC4: Rf_eval (svn/R-devel/src/main/eval.c:763)
==27368==    by 0x518FAC: Rf_ReplIteration (svn/R-devel/src/main/main.c:264)
==27368==    by 0x518FAC: Rf_ReplIteration (svn/R-devel/src/main/main.c:200)
==27368==    by 0x5192E7: R_ReplConsole (svn/R-devel/src/main/main.c:314)
==27368==    by 0x519374: run_Rmainloop (svn/R-devel/src/main/main.c:1113)
==27368==    by 0x417717: main (svn/R-devel/src/main/Rmain.c:29)
==27368==  Uninitialised value was created by a stack allocation
==27368==    at 0x19529170: c_STEP_3_AFFECT_ADA_KMEANS(Rcpp::Matrix<14,
Rcpp::PreserveStorage>, Rcpp::Vector<19, Rcpp::PreserveStorage>,
Rcpp::Vector<19, Rcpp::PreserveStorage>, int, int, int)
(/tmp/HistDAWass.Rcheck/00_pkg_src/HistDAWass/src/Utility_fun.cpp:1089)
</code>```

I isolated the function here, starting from row 1086

```<code>// [[Rcpp::export]]
List c_STEP_3_AFFECT_ADA_KMEANS(NumericMatrix lambdas,
                                List dIpro_m,
                                List dIpro_v, int ind, int k, int vars){
  NumericMatrix DiToClu(ind,k);
  int indiv,cluster,variable;
  NumericVector IDX(ind);
  double SSQ;

  for (indiv=0;indiv<ind;indiv++){
    for (cluster=0;cluster<k;cluster++){
       for (variable=0;variable<vars;variable++){
        DiToClu(indiv,cluster)=DiToClu(indiv,cluster)+
          (lambdas((variable*2),cluster)*(as<NumericMatrix>(dIpro_m[cluster]))(indiv,variable))+
          (lambdas((variable*2+1),cluster)*(as<NumericMatrix>(dIpro_v[cluster]))(indiv,variable));
      }
    }
    IDX[indiv]=which_min(DiToClu(indiv,_))+1;
    SSQ=SSQ+(min(DiToClu(indiv,_)));
  }
  List resu = List::create(Named("DiToClu") = DiToClu , _["IDX"] = IDX,_["SSQ"]=SSQ);
  return resu;
}
</code>```

I developed my package using Windows+Rstudio, I am not very familiar with tools like valgrind.
Since I cannot go un a Linux machine, how can I fix this issue?

答:
SSQ is not initialized but you do SSQ = SSQ + ... which can take any random value depending on what was in the memory before. You must initialize SSQ

```<code>double SSQ = 0;
</code>```

Body:
I checked my package (HistDAWass 1.0.3) on Windows+RStudio and it was OK.
I received a report from CRAN with this message:

 > ### Name: WH_adaptive.kmeans
 > ### Title: K-means of a dataset of histogram-valued data using adaptive
 > ###   Wasserstein distances
 > ### Aliases: WH_adaptive.kmeans
 >
 > ### ** Examples
 >
 > results=WH_adaptive.kmeans(x = BLOOD,k = 2, rep = 10,simplify =
TRUE,qua = 10,
standardize = TRUE)
==27368== Conditional jump or move depends on uninitialised value(s)
==27368==    at 0x4D6B2E: bcEval (svn/R-devel/src/main/eval.c:6517)
==27368==    by 0x4E8777: Rf_eval (svn/R-devel/src/main/eval.c:688)
==27368==    by 0x4EA336: R_execClosure (svn/R-devel/src/main/eval.c:1853)
==27368==    by 0x4EB113: Rf_applyClosure (svn/R-devel/src/main/eval.c:1779)
==27368==    by 0x4E8943: Rf_eval (svn/R-devel/src/main/eval.c:811)
==27368==    by 0x4ED2E1: do_set (svn/R-devel/src/main/eval.c:2920)
==27368==    by 0x4E8BC4: Rf_eval (svn/R-devel/src/main/eval.c:763)
==27368==    by 0x518FAC: Rf_ReplIteration (svn/R-devel/src/main/main.c:264)
==27368==    by 0x518FAC: Rf_ReplIteration (svn/R-devel/src/main/main.c:200)
==27368==    by 0x5192E7: R_ReplConsole (svn/R-devel/src/main/main.c:314)
==27368==    by 0x519374: run_Rmainloop (svn/R-devel/src/main/main.c:1113)
==27368==    by 0x417717: main (svn/R-devel/src/main/Rmain.c:29)
==27368==  Uninitialised value was created by a stack allocation
==27368==    at 0x19529170: c_STEP_3_AFFECT_ADA_KMEANS(Rcpp::Matrix<14,
Rcpp::PreserveStorage>, Rcpp::Vector<19, Rcpp::PreserveStorage>,
Rcpp::Vector<19, Rcpp::PreserveStorage>, int, int, int)
(/tmp/HistDAWass.Rcheck/00_pkg_src/HistDAWass/src/Utility_fun.cpp:1089)

I isolated the function here, starting from row 1086

// [[Rcpp::export]]
List c_STEP_3_AFFECT_ADA_KMEANS(NumericMatrix lambdas,
                                List dIpro_m,
                                List dIpro_v, int ind, int k, int vars){
  NumericMatrix DiToClu(ind,k);
  int indiv,cluster,variable;
  NumericVector IDX(ind);
  double SSQ;

  for (indiv=0;indiv<ind;indiv++){
    for (cluster=0;cluster<k;cluster++){
       for (variable=0;variable<vars;variable++){
        DiToClu(indiv,cluster)=DiToClu(indiv,cluster)+
          (lambdas((variable*2),cluster)*(as<NumericMatrix>(dIpro_m[cluster]))(indiv,variable))+
          (lambdas((variable*2+1),cluster)*(as<NumericMatrix>(dIpro_v[cluster]))(indiv,variable));
      }
    }
    IDX[indiv]=which_min(DiToClu(indiv,_))+1;
    SSQ=SSQ+(min(DiToClu(indiv,_)));
  }
  List resu = List::create(Named("DiToClu") = DiToClu , _["IDX"] = IDX,_["SSQ"]=SSQ);
  return resu;
}

I developed my package using Windows+Rstudio, I am not very familiar with tools like valgrind.
Since I cannot go un a Linux machine, how can I fix this issue?

Body:
SSQ is not initialized but you do SSQ = SSQ + ... which can take any random value depending on what was in the memory before. You must initialize SSQ

double SSQ = 0;


问:
resize image in xamarin without wrapping it in stacklayout
I have a lottie animation that is disabled after it is clicked again.

This is what my lottie animation looks like:

Paused:

Played:

As we can see the actual "Image" size is bigger. My row definition size is "Auto", and HeightRequest="180", WidthRequest="180" for the lottie animation.

What I want to happen here is if the lottie animation is disabled, my image that is overlapped with the animation will be (IsVisible) true.

But even if my HeightRequest="10" and WidthRequest="10" the image looks like this:

How can I achieve it to look like the size of the first image without wrapping it with stacklayout? I dont want to wrap it with stacklayout because I want my UI to be responsive.

If I use this code:

```<code>
               <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,55,0,0">
                    <Image Source="red_record"
                           HeightRequest="85"
                           WidthRequest="85"
                           x:Name="red_record_lottie"
                           IsVisible="True"
                           />
                </StackLayout>

</code>```

It will look like the desired output (for the UI):

But we know that the code will not make it responsive. How can I make it responsive?

答:
try using a frame since the image is circular u can have a frame and change the corner radius to make a circle.

https://montemagno.com/xamarin-forms-how-to-clip-images-with-rounded-corners/

this might help u and further explain my point of view

Body:
I have a lottie animation that is disabled after it is clicked again.

This is what my lottie animation looks like:

Paused:

Played:

As we can see the actual "Image" size is bigger. My row definition size is "Auto", and HeightRequest="180", WidthRequest="180" for the lottie animation.

What I want to happen here is if the lottie animation is disabled, my image that is overlapped with the animation will be (IsVisible) true.

But even if my HeightRequest="10" and WidthRequest="10" the image looks like this:

How can I achieve it to look like the size of the first image without wrapping it with stacklayout? I dont want to wrap it with stacklayout because I want my UI to be responsive.

If I use this code:

               <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,55,0,0">
                    <Image Source="red_record"
                           HeightRequest="85"
                           WidthRequest="85"
                           x:Name="red_record_lottie"
                           IsVisible="True"
                           />
                </StackLayout>

It will look like the desired output (for the UI):

But we know that the code will not make it responsive. How can I make it responsive?


问:
about ListView code
I am new to android and right now I am learning about ListView.

I was reading tutorials from bogotobogo.com when I saw this code:

```<code>ListView lv = getListView();
            lv.setTextFilterEnabled(true);
            *** lv.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView parent, View v,
                        int position, long id) {
                      // When clicked, show a toast with the TextView text
                    Toast.makeText(getApplicationContext(), ((TextView) v).getText(),
                    Toast.LENGTH_SHORT).show();
                }
            }); ***
</code>```

i was not able to understand  code from lv.setOnItemClickListener(new OnItemClickListener(); is it an argument?

Can some one help me to understand it?

答:
What that code is doing is implementing a new OnItemClickListener inline. The OnItemClickListener interface is basically a contract that says that an object will provide an implementation of the function onItemClick(....). Later on, when an item in your list gets clicked, the onItemClick function will be called and the AdapterView (thing that's instantiating and managing the list rows, the view - (the render code for a particular row), the position (the position in the list) and an id property which I never use so you can look up what that's for are being passed in.

Inline code like this always looks strange to me. There are a couple other ways to write this that I think make more intuitive sense. Just keep in mind that what you're doing is writing some code to get executed when a row in your list gets clicked.

1 - You can have your Activity implement OnItemClickListener

```<code>public class SomeActivity extends Activity implements OnItemClickListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourview);

        ListView lv = (ListView)findViewById(R.id.listView);
        lv.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
        //Your toast code goes in here
    }
}
</code>```

In this code you're having your main class implement the OnItemClickListener interface so setOnItemClickListener sees the main class (this) as an instance of OnItemClickListener. When a row in your list gets clicked the onItemClick function will get called.

You can also 2 - have your click listener come from an internal class.

```<code>public class SomeActivity extends Activity implements OnItemClickListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourview);

        ListView lv = (ListView)findViewById(R.id.listView);
        lv.setOnItemClickListener(new YourInternalClass());
    }

    class YourInternalClass implements View.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
            //Your toast code goes in here
        }
    }
}
</code>```

And really all three methods are doing the same thing: Providing the setOnItemClickListener with an instance of a View.OnItemClickListener class that will have it's onItemClick function called when a row in the list gets clicked.

Title: about ListView code

Body:
I am new to android and right now I am learning about ListView.

I was reading tutorials from bogotobogo.com when I saw this code:

ListView lv = getListView();
            lv.setTextFilterEnabled(true);
            *** lv.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView parent, View v,
                        int position, long id) {
                      // When clicked, show a toast with the TextView text
                    Toast.makeText(getApplicationContext(), ((TextView) v).getText(),
                    Toast.LENGTH_SHORT).show();
                }
            }); ***

i was not able to understand  code from lv.setOnItemClickListener(new OnItemClickListener(); is it an argument?

Can some one help me to understand it?

Body:
What that code is doing is implementing a new OnItemClickListener inline. The OnItemClickListener interface is basically a contract that says that an object will provide an implementation of the function onItemClick(....). Later on, when an item in your list gets clicked, the onItemClick function will be called and the AdapterView (thing that's instantiating and managing the list rows, the view - (the render code for a particular row), the position (the position in the list) and an id property which I never use so you can look up what that's for are being passed in.

Inline code like this always looks strange to me. There are a couple other ways to write this that I think make more intuitive sense. Just keep in mind that what you're doing is writing some code to get executed when a row in your list gets clicked.

1 - You can have your Activity implement OnItemClickListener

public class SomeActivity extends Activity implements OnItemClickListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourview);

        ListView lv = (ListView)findViewById(R.id.listView);
        lv.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
        //Your toast code goes in here
    }
}

In this code you're having your main class implement the OnItemClickListener interface so setOnItemClickListener sees the main class (this) as an instance of OnItemClickListener. When a row in your list gets clicked the onItemClick function will get called.

You can also 2 - have your click listener come from an internal class.

public class SomeActivity extends Activity implements OnItemClickListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourview);

        ListView lv = (ListView)findViewById(R.id.listView);
        lv.setOnItemClickListener(new YourInternalClass());
    }

    class YourInternalClass implements View.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
            //Your toast code goes in here
        }
    }
}

And really all three methods are doing the same thing: Providing the setOnItemClickListener with an instance of a View.OnItemClickListener class that will have it's onItemClick function called when a row in the list gets clicked.


问:
Difference B/W, WHERE and ON in SQL join Operation
Here is my test code for explaination

```<code>create table Test3(id integer, name varchar(100));
insert into Test3(id, name) values(1, "Vijay");
insert into Test3(id, name) values(2, "Sandy");
insert into Test3(id, name) values(3, "Rohit");
create table Test4(id integer, surname varchar(100));
insert into Test4(id, surname) values(1, "karma");
insert into Test4(id, surname) values(2, "sharma");
</code>```

Here is my Queries:

```<code>select Test3.id , Test3.name , Test4.surname from Test3,Test4 where Test3.id = Test4.id;
select Test3.id , Test3.name , Test4.surname from Test3 join Test4 on Test3.id = Test4.id;
</code>```

Both the above query statements resulted same as below:

1   Vijay   karma

2   Sandy   sharma

What is the difference in both queries internally and which one on more efficient?

答:
The performance will be equivalent in both the cases.

Select from multiple tables without join is nothing but a cross join. When you put a where clause to it, the query performs inner join.

Body:
Here is my test code for explaination

create table Test3(id integer, name varchar(100));
insert into Test3(id, name) values(1, "Vijay");
insert into Test3(id, name) values(2, "Sandy");
insert into Test3(id, name) values(3, "Rohit");
create table Test4(id integer, surname varchar(100));
insert into Test4(id, surname) values(1, "karma");
insert into Test4(id, surname) values(2, "sharma");

Here is my Queries:

select Test3.id , Test3.name , Test4.surname from Test3,Test4 where Test3.id = Test4.id;
select Test3.id , Test3.name , Test4.surname from Test3 join Test4 on Test3.id = Test4.id;

Both the above query statements resulted same as below:

1   Vijay   karma

2   Sandy   sharma

What is the difference in both queries internally and which one on more efficient?


问:
react-native :app:installDebug FAILED
Install APK debug to my device failed.

```<code>jianglinghuadeMacBook-Pro:hello jianglinghua$ react-native run-android
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug...
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
:app:preBuild UP-TO-DATE
......
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'MI NOTE LTE - 6.0.1'
Unable to install /Users/jianglinghua/Desktop/hello/android/app/build/outputs/apk/app-debug.apk
com.android.ddmlib.InstallException: Failed to establish session
    at com.android.ddmlib.Device.installPackages(Device.java:894)
    ........
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
:app:installDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to establish session

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 13.945 secs
</code>```

Could not install the app on the device, read the error above for details.
    Make sure you have an Android emulator running or a device connected and have
    set up your Android development environment:
    https://facebook.github.io/react-native/docs/android-setup.html

I look at my devices

```<code>jianglinghuadeMacBook-Pro:hello jianglinghua$ adb devices
List of devices attached
98333978    device
</code>```

答:
This works for me

Uninstall the app from your phone

cd android

gradlew clean

cd ..

react-native run-android

Title: react-native :app:installDebug FAILED

Body:
Install APK debug to my device failed.

jianglinghuadeMacBook-Pro:hello jianglinghua$ react-native run-android
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug...
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
:app:preBuild UP-TO-DATE
......
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'MI NOTE LTE - 6.0.1'
Unable to install /Users/jianglinghua/Desktop/hello/android/app/build/outputs/apk/app-debug.apk
com.android.ddmlib.InstallException: Failed to establish session
    at com.android.ddmlib.Device.installPackages(Device.java:894)
    ........
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
:app:installDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to establish session

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 13.945 secs

Could not install the app on the device, read the error above for details.
    Make sure you have an Android emulator running or a device connected and have
    set up your Android development environment:
    https://facebook.github.io/react-native/docs/android-setup.html

I look at my devices

jianglinghuadeMacBook-Pro:hello jianglinghua$ adb devices
List of devices attached
98333978    device


问:
How to choose an API gateway in Kubernetes?
We've used Zuul as API gateway for a while in Microservices scene, recently we decided to move to Kubernetes and choose a more cloud native way.

After some investigation and going through the Istio docs, we have some questions about API gateway selection in Kubernetes:

Which aspects should be considered when choosing an API gateway in Kubernetes?

Do we still need Zuul if we use Istio?

答: We use Kong Gateway. It's pretty simple and nginx based gateway. Easy to install and ready-to-go.</p>