问:
Arithmetic operation resulted in an overflow even after applying unchecked
Why do I get an overflow exception even if I apply the unchecked operator on an expression?

```<code>return GetCharStream().AsParallel().Aggregate<char, int[], int[]>(() => new int[26],
    (ca, c) =>
    {
        int i = char.ToUpper(c) - 'A';
        if (i > -1 && i < 26)
            unchecked { ca[i]++; }
        return ca;
    },
    (ma, la) =>
    {
        return ma.Zip(la, (t1, t2) => { return unchecked(t1 + t2); }).ToArray();
    },
    fResult => fResult);
</code>```

Update:

Even if I completely remove all arithmetic operations inside my code, I am still getting an arithmetic overflow exception:-

```<code>double[] CountAggregateParallel()
{
    //196386
    return GetCharStream().AsParallel().Aggregate(() => (new double[26]),
        LocalAccumulator,
        FinalAccumulator,
        fResult => fResult);
}

private static double[] FinalAccumulator(double[] ma, double[] la)
{
    return ma;
}

private static double[] LocalAccumulator(double[] ca, char c)
{
    return ca;
}

IEnumerable<char> GetCharStream()
{
    int i = 0;
    while (i < 200_000)
    {
        foreach (char c in str)
        {
            yield return c;
        }
        Console.WriteLine($"{i+1} iteration of str complete");
        i++;
    }
}
</code>```

The value of str variable:

```<code>string str = @"This chapter explains how unfavorable association is a threat to one’s position in devotional service and how by associating with saintly persons one can attain the highest platform of devotion.

The jīva who has received a human body, which is in itself most conducive toward achieving the Supreme Personality of Godhead, and who has situated himself in the duties of devotional service to the Lord becomes capable of realizing Him, the very identity of spiritual bliss. Such a person, fully dedicated to the Supreme Personality, is liberated from the influence of Māyā; even while continuing to reside in this world created by illusion he is totally untouched by it. Those souls, on the other hand, who are bound up by Māyā are devoted only to their bellies and genitals. They are impure, and by associating with them one will fall down into the dark pit of ignorance.

The emperor Purūravā, who was bewildered by the association of the heavenly lady Urvaśī, later became renounced after being separated from her. He thus sang a song expressing his contempt for womanly connection. He described that persons who are attached to the body of a woman (or a man) — which is simply a mass of skin, meat, blood, sinew, brain tissue, marrow and bones — are not much different from worms. What is the worth of the education, austerity, renunciation, reception of the Vedas, solitary living and silence of one whose mind becomes stolen away by the body of a woman? Learned men should distrust their six mental enemies, headed by lust, and thus avoid associating with women or with men who are controlled by women. After declaring these facts, King Purūravā, now freed from the illusion of material existence, attained realization of the Supreme Lord in His form as the indwelling Supersoul.

In conclusion, one who is intelligent should give up bad association and let himself become attracted to the company of saintly persons. By their transcendental instructions, the saintly devotees of the Lord can break the false attachments of one’s mind. Real saints are always liberated and devoted to the Supreme Personality of Godhead. In their association there are constant discussions about the Supreme Lord, by serving whom the spirit soul completely eradicates his material sins and obtains pure devotional service. And when one gains the devotional service of the Supreme Personality of Godhead, who is the original ocean of unlimited perfect qualities, what else remains to be gained?

Text 1: The Supreme Personality of Godhead said: Having achieved this human form of life, which affords one the opportunity to realize Me, and being situated in My devotional service, one can achieve Me, the reservoir of all pleasure and the Supreme Soul of all existence, residing within the heart of every living being.
Text 2: A person fixed in transcendental knowledge is freed from conditioned life by giving up his false identification with the products of the material modes of nature. Seeing these products as simply illusion, he avoids entanglement with the modes of nature, although constantly among them. Because the modes of nature and their products are simply not real, he does not accept them.
Text 3: One should never associate with materialists, those dedicated to gratifying their genitals and bellies. By following them one falls into the deepest pit of darkness, just like a blind man who follows another blind man.
Text 4: The following song was sung by the famous emperor Purūravā. When deprived of his wife, Urvaśī, he was at first bewildered, but by controlling his lamentation he began to feel detachment.
Text 5: When she was leaving him, even though he was naked he ran after her just like a madman and called out in great distress, “O my wife, O terrible lady! Please stop!”
Text 6: Although for many years Purūravā had enjoyed sex pleasure in the evening hours, still he was not satisfied by such insignificant enjoyment. His mind was so attracted to Urvaśī that he did not notice how the nights were coming and going.
Text 7: King Aila said: Alas, just see the extent of my delusion! This goddess was embracing me and held my neck in her grip. My heart was so polluted by lust that I had no idea how my life was passing.
Text 8: That lady cheated me so much that I did not even see the rising or setting of the sun. Alas, for so many years I passed my days in vain!
Text 9: Alas, although I am supposed to be a mighty emperor, the crown jewel of all kings on this earth, just see how my bewilderment has rendered me a toy animal in the hands of women!
Text 10: Although I was a powerful lord with great opulence, that woman gave me up as if I were no more than an insignificant blade of grass. And still, naked and without shame, I followed her, crying out to her like a madman.
Text 11: Where are my so-called great influence, power and sovereignty? Just like an ass being kicked in the face by his she-ass, I ran after that woman, who had already given me up.
Text 12: What is the use of a big education or the practice of austerities and renunciation, and what is the use of studying religious scriptures, of living in solitude and silence, if, after all that, one’s mind is stolen by a woman?
Text 13: To hell with me! I am such a fool that I didn’t even know what was good for me, although I arrogantly thought I was highly intelligent. Although I achieved the exalted position of a lord, I allowed myself to be conquered by women as if I were a bullock or a jackass.
Text 14: Even after I had served the so-called nectar of the lips of Urvaśī for many years, my lusty desires kept rising again and again within my heart and were never satisfied, just like a fire that can never be extinguished by the oblations of ghee poured into its flames.
Text 15: Who but the Supreme Personality of Godhead, who lies beyond material perception and is the Lord of self-satisfied sages, can possibly save my consciousness, which has been stolen by a prostitute?
Text 16: Because I allowed my intelligence to become dull and because I failed to control my senses, the great confusion in my mind did not go away, even though Urvaśī herself gave me wise counsel with well-spoken words.
Text 17: How can I blame her for my trouble when I myself am ignorant of my real, spiritual nature? I did not control my senses, and so I am like a person who mistakenly sees a harmless rope as a snake.
Text 18: What is this polluted body anyway — so filthy and full of bad odors? I was attracted by the fragrance and beauty of a woman’s body, but what are those so-called attractive features? They are simply a false covering created by illusion.
Texts 19-20: One can never decide whose property the body actually is. Does it belong to one’s parents, who have given birth to it, to one’s wife, who gives it pleasure, or to one’s employer, who orders the body around? Is it the property of the funeral fire or of the dogs and jackals who may ultimately devour it? Is it the property of the indwelling soul, who partakes in its happiness and distress, or does the body belong to intimate friends who encourage and help it? Although a man never definitely ascertains the proprietor of the body, he becomes most attached to it. The material body is a polluted material form heading toward a lowly destination, yet when a man stares at the face of a woman he thinks, “What a good-looking lady! What a charming nose she’s got, and see her beautiful smile!”
Text 21: What difference is there between ordinary worms and persons who try to enjoy this material body composed of skin, flesh, blood, muscle, fat, marrow, bone, stool, urine and pus?
Text 22: Yet even one who theoretically understands the actual nature of the body should never associate with women or with men attached to women. After all, the contact of the senses with their objects inevitably agitates the mind.
Text 23: Because the mind is not disturbed by that which is neither seen nor heard, the mind of a person who restricts the material senses will automatically be checked in its material activities and become pacified.
Text 24: Therefore one should never let his senses associate freely with women or with men attached to women. Even those who are highly learned cannot trust the six enemies of the mind; what to speak, then, of foolish persons like me.
Text 25: The Supreme Personality of Godhead said: Having thus chanted this song, Mahārāja Purūravā, eminent among the demigods and human beings, gave up the position he had achieved in the planet of Urvaśī. His illusion cleansed away by transcendental knowledge, he understood Me to be the Supreme Soul within his heart and so at last achieved peace.
Text 26: An intelligent person should therefore reject all bad association and instead take up the association of saintly devotees, whose words cut off the excessive attachment of one’s mind.
Text 27: My devotees fix their minds on Me and do not depend upon anything material. They are always peaceful, endowed with equal vision, and free from possessiveness, false ego, duality and greed.
Text 28: O greatly fortunate Uddhava, in the association of such saintly devotees there is constant discussion of Me, and those partaking in this chanting and hearing of My glories are certainly purified of all sins.
Text 29: Whoever hears, chants and respectfully takes to heart these topics about Me becomes faithfully dedicated to Me and thus achieves My devotional service.
Text 30: What more remains to be accomplished for the perfect devotee after achieving devotional service unto Me, the Supreme Absolute Truth, whose qualities are innumerable and who am the embodiment of all ecstatic experience?
Text 31: Just as cold, fear and darkness are eradicated for one who has approached the sacrificial fire, so dullness, fear and ignorance are destroyed for one engaged in serving the devotees of the Lord.
Text 32: The devotees of the Lord, peacefully fixed in absolute knowledge, are the ultimate shelter for those who are repeatedly rising and falling within the fearful ocean of material life. Such devotees are just like a strong boat that comes to rescue persons who are at the point of drowning.
Text 33: Just as food is the life of all creatures, just as I am the ultimate shelter for the distressed, and just as religion is the wealth of those who are passing away from this world, so My devotees are the only refuge of persons fearful of falling into a miserable condition of life.
Text 34: My devotees bestow divine eyes, whereas the sun allows only external sight, and that only when it is risen in the sky. My devotees are one’s real worshipable deities and real family; they are one’s own self, and ultimately they are nondifferent from Me.
Text 35: Thus losing his desire to be on the same planet as Urvaśī, Mahārāja Purūravā began to wander the earth free of all material association and completely satisfied within the self.";
</code>```

答:
I managed to reproduce this issue with the simplified code below. It seems to me like a bug, or at least as an undocumented limitation of the Aggregate method. It fails after enumerating a number of around Int32.MaxValue elements.

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    static void Main(string[] args)
    {
        var result = GetNumbers().AsParallel().WithDegreeOfParallelism(1)
            .Aggregate((long)0, (acc, i) => acc + i, (a, b) => a + b, acc => acc);
        Console.WriteLine($"Result: {result:#,0}");
    }

    static IEnumerable<uint> GetNumbers()
    {
        for (uint i = 0; i < UInt32.MaxValue; i++)
        {
            if (i % 10_000_000 == 0 || i > (Int32.MaxValue - 1000))
                Console.WriteLine($"Yielding: {i:#,0}");
            yield return i;
        }
    }
}
</code>```

The exception thrown is:

System.OverflowException: Arithmetic operation resulted in an overflow.
   at System.Linq.Parallel.PartitionedDataSource`1.ContiguousChunkLazyEnumerator.MoveNext(T& currentElement, Int32& currentKey)
   at System.Linq.Parallel.AssociativeAggregationOperator`3.AssociativeAggregationOperatorEnumerator`1.MoveNext(TIntermediate& currentElement, Int32& currentKey)
   at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
   at System.Linq.Parallel.SpoolingTaskBase.Work()
   at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
   at System.Linq.Parallel.QueryTask.RunTaskSynchronously(Object o)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
```

The exact number of iterations before the exception is deterministic, and depends on the value passed to WithDegreeOfParallelism.

WithDegreeOfParallelism(1): 2,147,483,767

WithDegreeOfParallelism(2): 2,147,483,887

WithDegreeOfParallelism(3): 2,147,484,007

WithDegreeOfParallelism(4): 2,147,484,127

WithDegreeOfParallelism(5): 2,147,484,247

.NET Core 3.1.3, .NET Framework 4.8.4150.0, C# 8, Visual Studio 16.5.4

Body:
Why do I get an overflow exception even if I apply the unchecked operator on an expression?

return GetCharStream().AsParallel().Aggregate<char, int[], int[]>(() => new int[26],
    (ca, c) =>
    {
        int i = char.ToUpper(c) - 'A';
        if (i > -1 && i < 26)
            unchecked { ca[i]++; }
        return ca;
    },
    (ma, la) =>
    {
        return ma.Zip(la, (t1, t2) => { return unchecked(t1 + t2); }).ToArray();
    },
    fResult => fResult);

Update:

Even if I completely remove all arithmetic operations inside my code, I am still getting an arithmetic overflow exception:-

double[] CountAggregateParallel()
{
    //196386
    return GetCharStream().AsParallel().Aggregate(() => (new double[26]),
        LocalAccumulator,
        FinalAccumulator,
        fResult => fResult);
}

private static double[] FinalAccumulator(double[] ma, double[] la)
{
    return ma;
}

private static double[] LocalAccumulator(double[] ca, char c)
{
    return ca;
}

IEnumerable<char> GetCharStream()
{
    int i = 0;
    while (i < 200_000)
    {
        foreach (char c in str)
        {
            yield return c;
        }
        Console.WriteLine($"{i+1} iteration of str complete");
        i++;
    }
}

The value of str variable:

string str = @"This chapter explains how unfavorable association is a threat to one’s position in devotional service and how by associating with saintly persons one can attain the highest platform of devotion.

The jīva who has received a human body, which is in itself most conducive toward achieving the Supreme Personality of Godhead, and who has situated himself in the duties of devotional service to the Lord becomes capable of realizing Him, the very identity of spiritual bliss. Such a person, fully dedicated to the Supreme Personality, is liberated from the influence of Māyā; even while continuing to reside in this world created by illusion he is totally untouched by it. Those souls, on the other hand, who are bound up by Māyā are devoted only to their bellies and genitals. They are impure, and by associating with them one will fall down into the dark pit of ignorance.

The emperor Purūravā, who was bewildered by the association of the heavenly lady Urvaśī, later became renounced after being separated from her. He thus sang a song expressing his contempt for womanly connection. He described that persons who are attached to the body of a woman (or a man) — which is simply a mass of skin, meat, blood, sinew, brain tissue, marrow and bones — are not much different from worms. What is the worth of the education, austerity, renunciation, reception of the Vedas, solitary living and silence of one whose mind becomes stolen away by the body of a woman? Learned men should distrust their six mental enemies, headed by lust, and thus avoid associating with women or with men who are controlled by women. After declaring these facts, King Purūravā, now freed from the illusion of material existence, attained realization of the Supreme Lord in His form as the indwelling Supersoul.

In conclusion, one who is intelligent should give up bad association and let himself become attracted to the company of saintly persons. By their transcendental instructions, the saintly devotees of the Lord can break the false attachments of one’s mind. Real saints are always liberated and devoted to the Supreme Personality of Godhead. In their association there are constant discussions about the Supreme Lord, by serving whom the spirit soul completely eradicates his material sins and obtains pure devotional service. And when one gains the devotional service of the Supreme Personality of Godhead, who is the original ocean of unlimited perfect qualities, what else remains to be gained?

Text 1: The Supreme Personality of Godhead said: Having achieved this human form of life, which affords one the opportunity to realize Me, and being situated in My devotional service, one can achieve Me, the reservoir of all pleasure and the Supreme Soul of all existence, residing within the heart of every living being.
Text 2: A person fixed in transcendental knowledge is freed from conditioned life by giving up his false identification with the products of the material modes of nature. Seeing these products as simply illusion, he avoids entanglement with the modes of nature, although constantly among them. Because the modes of nature and their products are simply not real, he does not accept them.
Text 3: One should never associate with materialists, those dedicated to gratifying their genitals and bellies. By following them one falls into the deepest pit of darkness, just like a blind man who follows another blind man.
Text 4: The following song was sung by the famous emperor Purūravā. When deprived of his wife, Urvaśī, he was at first bewildered, but by controlling his lamentation he began to feel detachment.
Text 5: When she was leaving him, even though he was naked he ran after her just like a madman and called out in great distress, “O my wife, O terrible lady! Please stop!”
Text 6: Although for many years Purūravā had enjoyed sex pleasure in the evening hours, still he was not satisfied by such insignificant enjoyment. His mind was so attracted to Urvaśī that he did not notice how the nights were coming and going.
Text 7: King Aila said: Alas, just see the extent of my delusion! This goddess was embracing me and held my neck in her grip. My heart was so polluted by lust that I had no idea how my life was passing.
Text 8: That lady cheated me so much that I did not even see the rising or setting of the sun. Alas, for so many years I passed my days in vain!
Text 9: Alas, although I am supposed to be a mighty emperor, the crown jewel of all kings on this earth, just see how my bewilderment has rendered me a toy animal in the hands of women!
Text 10: Although I was a powerful lord with great opulence, that woman gave me up as if I were no more than an insignificant blade of grass. And still, naked and without shame, I followed her, crying out to her like a madman.
Text 11: Where are my so-called great influence, power and sovereignty? Just like an ass being kicked in the face by his she-ass, I ran after that woman, who had already given me up.
Text 12: What is the use of a big education or the practice of austerities and renunciation, and what is the use of studying religious scriptures, of living in solitude and silence, if, after all that, one’s mind is stolen by a woman?
Text 13: To hell with me! I am such a fool that I didn’t even know what was good for me, although I arrogantly thought I was highly intelligent. Although I achieved the exalted position of a lord, I allowed myself to be conquered by women as if I were a bullock or a jackass.
Text 14: Even after I had served the so-called nectar of the lips of Urvaśī for many years, my lusty desires kept rising again and again within my heart and were never satisfied, just like a fire that can never be extinguished by the oblations of ghee poured into its flames.
Text 15: Who but the Supreme Personality of Godhead, who lies beyond material perception and is the Lord of self-satisfied sages, can possibly save my consciousness, which has been stolen by a prostitute?
Text 16: Because I allowed my intelligence to become dull and because I failed to control my senses, the great confusion in my mind did not go away, even though Urvaśī herself gave me wise counsel with well-spoken words.
Text 17: How can I blame her for my trouble when I myself am ignorant of my real, spiritual nature? I did not control my senses, and so I am like a person who mistakenly sees a harmless rope as a snake.
Text 18: What is this polluted body anyway — so filthy and full of bad odors? I was attracted by the fragrance and beauty of a woman’s body, but what are those so-called attractive features? They are simply a false covering created by illusion.
Texts 19-20: One can never decide whose property the body actually is. Does it belong to one’s parents, who have given birth to it, to one’s wife, who gives it pleasure, or to one’s employer, who orders the body around? Is it the property of the funeral fire or of the dogs and jackals who may ultimately devour it? Is it the property of the indwelling soul, who partakes in its happiness and distress, or does the body belong to intimate friends who encourage and help it? Although a man never definitely ascertains the proprietor of the body, he becomes most attached to it. The material body is a polluted material form heading toward a lowly destination, yet when a man stares at the face of a woman he thinks, “What a good-looking lady! What a charming nose she’s got, and see her beautiful smile!”
Text 21: What difference is there between ordinary worms and persons who try to enjoy this material body composed of skin, flesh, blood, muscle, fat, marrow, bone, stool, urine and pus?
Text 22: Yet even one who theoretically understands the actual nature of the body should never associate with women or with men attached to women. After all, the contact of the senses with their objects inevitably agitates the mind.
Text 23: Because the mind is not disturbed by that which is neither seen nor heard, the mind of a person who restricts the material senses will automatically be checked in its material activities and become pacified.
Text 24: Therefore one should never let his senses associate freely with women or with men attached to women. Even those who are highly learned cannot trust the six enemies of the mind; what to speak, then, of foolish persons like me.
Text 25: The Supreme Personality of Godhead said: Having thus chanted this song, Mahārāja Purūravā, eminent among the demigods and human beings, gave up the position he had achieved in the planet of Urvaśī. His illusion cleansed away by transcendental knowledge, he understood Me to be the Supreme Soul within his heart and so at last achieved peace.
Text 26: An intelligent person should therefore reject all bad association and instead take up the association of saintly devotees, whose words cut off the excessive attachment of one’s mind.
Text 27: My devotees fix their minds on Me and do not depend upon anything material. They are always peaceful, endowed with equal vision, and free from possessiveness, false ego, duality and greed.
Text 28: O greatly fortunate Uddhava, in the association of such saintly devotees there is constant discussion of Me, and those partaking in this chanting and hearing of My glories are certainly purified of all sins.
Text 29: Whoever hears, chants and respectfully takes to heart these topics about Me becomes faithfully dedicated to Me and thus achieves My devotional service.
Text 30: What more remains to be accomplished for the perfect devotee after achieving devotional service unto Me, the Supreme Absolute Truth, whose qualities are innumerable and who am the embodiment of all ecstatic experience?
Text 31: Just as cold, fear and darkness are eradicated for one who has approached the sacrificial fire, so dullness, fear and ignorance are destroyed for one engaged in serving the devotees of the Lord.
Text 32: The devotees of the Lord, peacefully fixed in absolute knowledge, are the ultimate shelter for those who are repeatedly rising and falling within the fearful ocean of material life. Such devotees are just like a strong boat that comes to rescue persons who are at the point of drowning.
Text 33: Just as food is the life of all creatures, just as I am the ultimate shelter for the distressed, and just as religion is the wealth of those who are passing away from this world, so My devotees are the only refuge of persons fearful of falling into a miserable condition of life.
Text 34: My devotees bestow divine eyes, whereas the sun allows only external sight, and that only when it is risen in the sky. My devotees are one’s real worshipable deities and real family; they are one’s own self, and ultimately they are nondifferent from Me.
Text 35: Thus losing his desire to be on the same planet as Urvaśī, Mahārāja Purūravā began to wander the earth free of all material association and completely satisfied within the self.";

Body:
I managed to reproduce this issue with the simplified code below. It seems to me like a bug, or at least as an undocumented limitation of the Aggregate method. It fails after enumerating a number of around Int32.MaxValue elements.

using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    static void Main(string[] args)
    {
        var result = GetNumbers().AsParallel().WithDegreeOfParallelism(1)
            .Aggregate((long)0, (acc, i) => acc + i, (a, b) => a + b, acc => acc);
        Console.WriteLine($"Result: {result:#,0}");
    }

    static IEnumerable<uint> GetNumbers()
    {
        for (uint i = 0; i < UInt32.MaxValue; i++)
        {
            if (i % 10_000_000 == 0 || i > (Int32.MaxValue - 1000))
                Console.WriteLine($"Yielding: {i:#,0}");
            yield return i;
        }
    }
}

The exception thrown is:

System.OverflowException: Arithmetic operation resulted in an overflow.
   at System.Linq.Parallel.PartitionedDataSource`1.ContiguousChunkLazyEnumerator.MoveNext(T& currentElement, Int32& currentKey)
   at System.Linq.Parallel.AssociativeAggregationOperator`3.AssociativeAggregationOperatorEnumerator`1.MoveNext(TIntermediate& currentElement, Int32& currentKey)
   at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
   at System.Linq.Parallel.SpoolingTaskBase.Work()
   at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
   at System.Linq.Parallel.QueryTask.RunTaskSynchronously(Object o)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)

The exact number of iterations before the exception is deterministic, and depends on the value passed to WithDegreeOfParallelism.

WithDegreeOfParallelism(1): 2,147,483,767

WithDegreeOfParallelism(2): 2,147,483,887

WithDegreeOfParallelism(3): 2,147,484,007

WithDegreeOfParallelism(4): 2,147,484,127

WithDegreeOfParallelism(5): 2,147,484,247

.NET Core 3.1.3, .NET Framework 4.8.4150.0, C# 8, Visual Studio 16.5.4


来源: stackexchange

问:
Question for Twilio whatsapp api phone number
I am trying to find WhatsApp API service as a tool to send messages to our client.

However, I am confused about Twilio WhatsApp API phone number.

If I use their service (API), do I need to buy their phone number? Can I use my phone number to send messages to clients?

If I buy their phone number, can this number be kept until I terminate the contract? (I'm worried that I always need to change the number)

Can this number also be used as a regular phone call or SMS?

Can Twilio keep WhatsApp always online? (I have tried other companies, but they cannot do this. Once WhatsApp is closed, it will stop sending messages.)

Can Twilio WhatsApp API support send to group function?

What is a template? (Assuming I need to send an alert based on different sensors, can I change the body part to send it to the user? Or do I need to register another template first)?
image-body part

Does Twilio have email / WhatsApp to ask questions?

答:
If I use their service (api), do I need to buy their phone number? Can I use my phone number to send messages to clients?

Answer: Today, you will use need to use a Twilio number you WhatsApp enable. You could always port in your number to Twilio, if it is in a supported country.

If I buy their phone number, can this number be kept until I terminate the contract? (I'm worried that I always need to change the number)

Answer: Yes.

Can this number also be used as a regular phone call or SMS?

Answer: Yes.

Can Twilio keep whatsapp always online? (I have tried other companies, but they cannot do this. Once whatsapp is closed, it will stop sending messages.)

Answer: Twilio WhatsApp is an API, there is no application to keep online.

Can Twilio whatsapp api support send to group function?

Answer: No.

What is a template? (Assuming I need to send an alert based on different sensors, can I change the body part to send it to the user? Or do I need to register another template first)? image-body part

Answer: Templates are described here, the text between the curly brackets can be replaced with customized text.

Does twilio have email / whatsapp to ask questions?

Answer: Not sure I understand this question. Twilio Sendgrid does offer an Email API but this is separate/distinct from the WhatsApp API. The Twilio WhatsApp integration allows you to seamlessly use the Twilio Messages resources to send SMS or WhatsApp messages, depending on how you prefix the From/To.

ContentLicense: CC BY-SA 4.0


问:
Executing a python file via crontabs is resulting in a FileNotFoundError
I have a python script which I want to run on a daily basis. I'm using crontabs for this on my Mac with the following command:

```<code>*/1 * * * * /opt/anaconda3/bin/python *absolute_path*/dynamic_dataset.py
</code>```

It is working fine! But the log shows that I am running into a "FileNotFoundError". I am reading a csv and h5 file in which are not found. How can I make crontab also use these files?

Many thanks in advance!

答:
I found the problem myself. For python to find the other files you have to execute the python in the directory of the files. So what I did is to navigate to the directory in the cronjob first.</p>

```<code>*/1 * * * * cd *path*/Local && /opt/anaconda3/bin/python *path*/Local/dynamic_dataset.py
</code>```

Body:
I have a python script which I want to run on a daily basis. I'm using crontabs for this on my Mac with the following command:

*/1 * * * * /opt/anaconda3/bin/python *absolute_path*/dynamic_dataset.py

It is working fine! But the log shows that I am running into a "FileNotFoundError". I am reading a csv and h5 file in which are not found. How can I make crontab also use these files?

Many thanks in advance!

Body:
I found the problem myself. For python to find the other files you have to execute the python in the directory of the files. So what I did is to navigate to the directory in the cronjob first.

*/1 * * * * cd *path*/Local && /opt/anaconda3/bin/python *path*/Local/dynamic_dataset.py


问:
How to wrap to text when text is long
I have made a report In which I want to wrap words When the text is longer than the line But the result is the text has been entered below the line Causing all results to be out of line. How to......

```<code><detail>
    <band height="20" splitType="Stretch">
        <textField>
            <reportElement stretchType="RelativeToTallestObject" x="259" y="2" width="48" height="17"/>
            <textElement textAlignment="Center" verticalAlignment="Top">
                <font fontName="AngsanaUPC" size="13" pdfFontName="AngsanaUPC" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{TRDATE}]]></textFieldExpression>
        </textField>
        <textField isStretchWithOverflow="true">
            <reportElement x="312" y="2" width="113" height="17"/>
            <textElement verticalAlignment="Middle">
                <font fontName="AngsanaUPC" size="13" pdfFontName="AngsanaUPC" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{LOCATION}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="426" y="2" width="58" height="17"/>
            <textElement verticalAlignment="Middle">
                <font fontName="AngsanaUPC" size="14" pdfFontName="AngsanaUPC" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{SAVENAME}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="486" y="2" width="59" height="17"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">
                <font fontName="AngsanaUPC" size="13" pdfFontName="AngsanaUPC" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{SAVEDATE}]]></textFieldExpression>
        </textField>
        <line>
            <reportElement x="10" y="18" width="535" height="1"/>
            <graphicElement>
                <pen lineWidth="0.25"/>
            </graphicElement>
        </line>
        <textField>
            <reportElement x="11" y="1" width="33" height="17"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">
                <font fontName="AngsanaUPC" size="13" pdfFontName="AngsanaUPC" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{SEQ}]]></textFieldExpression>
        </textField>
        <textField isStretchWithOverflow="true">
            <reportElement x="47" y="2" width="212" height="16"/>
            <textElement verticalAlignment="Middle">
                <font fontName="AngsanaUPC" size="13" pdfFontName="AngsanaUPC" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{COURSENAME}]]></textFieldExpression>
        </textField>
    </band>
</detail>
</code>```

Example output for report:

Desired result:

答: Select all the elements in the band and set Stretch type = "Relative to Tallest Objest"</p>

Title: How to wrap to text when text is long

Body:
I have made a report In which I want to wrap words When the text is longer than the line But the result is the text has been entered below the line Causing all results to be out of line. How to......

<detail>
    <band height="20" splitType="Stretch">
        <textField>
            <reportElement stretchType="RelativeToTallestObject" x="259" y="2" width="48" height="17"/>
            <textElement textAlignment="Center" verticalAlignment="Top">

            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{TRDATE}]]></textFieldExpression>
        </textField>
        <textField isStretchWithOverflow="true">
            <reportElement x="312" y="2" width="113" height="17"/>
            <textElement verticalAlignment="Middle">

            </textElement>
            <textFieldExpression><![CDATA[$F{LOCATION}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="426" y="2" width="58" height="17"/>
            <textElement verticalAlignment="Middle">

            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{SAVENAME}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="486" y="2" width="59" height="17"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">

            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{SAVEDATE}]]></textFieldExpression>
        </textField>
        <line>
            <reportElement x="10" y="18" width="535" height="1"/>
            <graphicElement>
                <pen lineWidth="0.25"/>
            </graphicElement>
        </line>
        <textField>
            <reportElement x="11" y="1" width="33" height="17"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">

            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$F{SEQ}]]></textFieldExpression>
        </textField>
        <textField isStretchWithOverflow="true">
            <reportElement x="47" y="2" width="212" height="16"/>
            <textElement verticalAlignment="Middle">

            </textElement>
            <textFieldExpression><![CDATA[$F{COURSENAME}]]></textFieldExpression>
        </textField>
    </band>
</detail>

Example output for report:

Desired result:


问:
make site available only from given ip
Is it possible to set my entaire web application available only from given ip address ? Can I use global.asax or something to place the code only in one place and be able to remove this freely ?

Thanks for any hints

答:
Yes it is possible. You can get the system IP address from where it is accessed and can block.

Request.Params["REMOTE_ADDR"]

You can see this link for details

Best way to restrict access by IP address?

ContentLicense: CC BY-SA 3.0

Title: make site available only from given ip


问:
PowerShell Adding
I need your help on this please,

I m parsing another xml file, remove the nodes that i don t need, and save the same document, but it`s removes the xml declaration to.

Is there any way that don`t remove it? Or adding again?

I`ve got this litle xml file. But i need to add this declaration on this on the first line:

<'?xml version="1.0" encoding="UTF-8" standalone="yes"?'>

I tried a lot of ways, but or give -me error or an exception

```<code><METATRANSCRIPT:METATRANSCRIPT xmlns:METATRANSCRIPT="http://www.mpi.nl/IMDI/Schema/IMDI" xmlns="http://www.mpi.nl/IMDI/Schema/IMDI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ArchiveHandle="hdl:2196/00-0000-0000-0013-5776-9" Date="2018-12-17" FormatId="IMDI 3.04" Originator="CMDI Maker by CLASS - Cologne Language Archive Services" Type="SESSION" Version="1.0" xsi:schemaLocation="http://www.mpi.nl/IMDI/Schema/IMDI http://www.mpi.nl/IMDI/Schema/IMDI_3.0.xsd">
   <Location>
     <Continent Link="http://www.mpi.nl/IMDI/Schema/Continents.xml"  Type="ClosedVocabulary">Oceania</Continent>
     <Country Link="http://www.mpi.nl/IMDI/Schema/Countries.xml"  Type="OpenVocabulary">Vanuatu</Country>
     <Region>Shefa Province</Region>
     <Address>Tongamea village Emae island</Address>
  </Location>
</METATRANSCRIPT:METATRANSCRIPT>
</code>```

This is my code:

```<code>     [xml]$File = gc c:\\Source\Fakamae_2018005_KM.xml -Raw

     foreach ($meta in $File)
     {$File =($meta.xml,[xml]$File.GetElementsByTagName("METATRANSCRIPT:METATRANSCRIPT")[0].OuterXml)}
              $File.Save('c:\\Source\Output\Result.xml')
</code>```

This is my error:

```<code>Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of
this node, because the specified node is the wrong type."
At line:9 char:10
+          $File =($meta.xml,[xml]$File.GetElementsByTagName("METATRANS ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException
</code>```

Thanks a lot for any help.

答:
From your earlier question I gather that you strip large xml files from all unwanted stuff and end up with only the METATRANSCRIPT:METATRANSCRIPT element.

On top of that you want to re-add the XML declaration.

Since you are treating the XML files as plain text to do the stripping, you can add the declaration like this:

```<code>Get-ChildItem -Path 'Path\To\XML\Files' -Filter '*.xml' -File | ForEach-Object {
    # do your routine on the xml in $_.FullName leaving only the METATRANSCRIPT element

    # if this leads to a string array in memory, just use that as-is
    $strippedXmlText = Strip-MyXml -Path $_.FullName

    # otherwise, if this leads to a temporary file, read it back in as string array:
    # $strippedXmlText = Get-Content -Path 'Path\To\The\Temp\File'

    $declaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    # rewrite that file by prepending the declaration line to it
    Set-Content -Path 'Path\To\The\Output\File' -Value $declaration, $strippedXmlText -Encoding UTF8
}
</code>```

Title: PowerShell Adding

Body:
I need your help on this please,

I m parsing another xml file, remove the nodes that i don t need, and save the same document, but it`s removes the xml declaration to.

Is there any way that don`t remove it? Or adding again?

I`ve got this litle xml file. But i need to add this declaration on this on the first line:

<'?xml version="1.0" encoding="UTF-8" standalone="yes"?'>

I tried a lot of ways, but or give -me error or an exception

<METATRANSCRIPT:METATRANSCRIPT xmlns:METATRANSCRIPT="http://www.mpi.nl/IMDI/Schema/IMDI" xmlns="http://www.mpi.nl/IMDI/Schema/IMDI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ArchiveHandle="hdl:2196/00-0000-0000-0013-5776-9" Date="2018-12-17" FormatId="IMDI 3.04" Originator="CMDI Maker by CLASS - Cologne Language Archive Services" Type="SESSION" Version="1.0" xsi:schemaLocation="http://www.mpi.nl/IMDI/Schema/IMDI http://www.mpi.nl/IMDI/Schema/IMDI_3.0.xsd">
   <Location>
     <Continent Link="http://www.mpi.nl/IMDI/Schema/Continents.xml"  Type="ClosedVocabulary">Oceania</Continent>
     <Country Link="http://www.mpi.nl/IMDI/Schema/Countries.xml"  Type="OpenVocabulary">Vanuatu</Country>
     <Region>Shefa Province</Region>
     <Address>Tongamea village Emae island</Address>
  </Location>
</METATRANSCRIPT:METATRANSCRIPT>

This is my code:

     [xml]$File = gc c:\\Source\Fakamae_2018005_KM.xml -Raw

     foreach ($meta in $File)
     {$File =($meta.xml,[xml]$File.GetElementsByTagName("METATRANSCRIPT:METATRANSCRIPT")[0].OuterXml)}
              $File.Save('c:\\Source\Output\Result.xml')

This is my error:

Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of
this node, because the specified node is the wrong type."
At line:9 char:10
+          $File =($meta.xml,[xml]$File.GetElementsByTagName("METATRANS ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

Thanks a lot for any help.

Body:
From your earlier question I gather that you strip large xml files from all unwanted stuff and end up with only the METATRANSCRIPT:METATRANSCRIPT element.

On top of that you want to re-add the XML declaration.

Since you are treating the XML files as plain text to do the stripping, you can add the declaration like this:

Get-ChildItem -Path 'Path\To\XML\Files' -Filter '*.xml' -File | ForEach-Object {
    # do your routine on the xml in $_.FullName leaving only the METATRANSCRIPT element

    # if this leads to a string array in memory, just use that as-is
    $strippedXmlText = Strip-MyXml -Path $_.FullName

    # otherwise, if this leads to a temporary file, read it back in as string array:
    # $strippedXmlText = Get-Content -Path 'Path\To\The\Temp\File'

    $declaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    # rewrite that file by prepending the declaration line to it
    Set-Content -Path 'Path\To\The\Output\File' -Value $declaration, $strippedXmlText -Encoding UTF8
}


问:
why graphviz dot can not open a dot file?
I am compiling a dot file to a jpg using dot program about graphviz.This is my command:

```<code>dot a.dot -o 1.ps
</code>```

The out put error is:

```<code>Error: dot: can't open a.dot
</code>```

This is my dot file(a.dot) content:

```<code>digraph abc{
  a;
  b;
  a -> b;
}
</code>```

I have tried:

```<code>dot -Tjpg -Gdpi=331 a.dot -o a.jpg
dot -Tps a.dot -o a.ps
</code>```

Why would this happen? How to fix?

OS:Windows 7 X64

dot version: dot - graphviz version 2.38.0 (20140413.2041)

答:
try it</p>

```<code>dot -Tpng "a.dot" -o "a.png"
</code>```

Body:
I am compiling a dot file to a jpg using dot program about graphviz.This is my command:

dot a.dot -o 1.ps

The out put error is:

Error: dot: can't open a.dot

This is my dot file(a.dot) content:

digraph abc{
  a;
  b;
  a -> b;
}

I have tried:

dot -Tjpg -Gdpi=331 a.dot -o a.jpg
dot -Tps a.dot -o a.ps

Why would this happen? How to fix?

OS:Windows 7 X64

dot version: dot - graphviz version 2.38.0 (20140413.2041)

Body:
try it

dot -Tpng "a.dot" -o "a.png"


问:
How can I formulate the function solution?

x = [1, 2, 3, 4]
t = []
c = []
for(i = 0; i<x.length; i++){
   function solution(){
       t = Math.pow(x, 2)
       c = t[i]++
    return c
   }
}```

The function needs to:

Count the squares of the array numbers

Then to get sum of squared (I am not sure if I wrote it correct, LOL) numbers. Thanks!

答:
var result = [1, 2, 3, 4].map(n => Math.pow(n, 2)).reduce((acc, val) => acc + val, 0);

console.log(result);```

Body:
x = [1, 2, 3, 4]
t = []
c = []
for(i = 0; i<x.length; i++){
   function solution(){
       t = Math.pow(x, 2)
       c = t[i]++
    return c
   }
}

The function needs to:

Count the squares of the array numbers

Then to get sum of squared (I am not sure if I wrote it correct, LOL) numbers. Thanks!


问:
Deploy a simple python bot on Openshift
This is a very simple pure python app (not Django or Flask).

What is the step-by-step and correct way of deploying this app on Openshift ?, so that it runs forever.

Code:

```<code>import requests as rq
from bs4 import BeautifulSoup as bs
import time
url = "https://apod.nasa.gov/apod/astropix.html"
page = rq.get(url).content
soup = bs(page, 'html.parser')
response = soup.find('img')
if response == None:
    imglink = soup.find('iframe')['src']
else:
    imglink = 'https://apod.nasa.gov/apod/' + response['src']
def main():
    while True:
        sess = rq.Session()
        cid='@*********'
        turl = 'https://api.telegram.org/bot****************/'
        if response == None:
            imglink = soup.find('iframe')['src']
            params = {'chat_id':cid,'text':imglink}
            sess.post(turl + 'sendMessage', data=params)
        else:
            imglink = 'https://apod.nasa.gov/apod/' + response['src']
            title = soup.find('b').get_text()
            params = {'chat_id':cid,'photo':imglink,'caption':title}
            sess.post(turl + 'sendPhoto', data=params)
        time.sleep(30)
if __name__ == '__main__':
    main()
</code>```

答:
use following on commands on terminal

oc login -u admin

After login in openshift cluster create new project

oc new-project python

Create an application in project python

oc new-app python~https:// repository url where your application is
located --name myapp

get the status of created pod

oc status

expose the service of pod

oc expose svc/myapp

Title: Deploy a simple python bot on Openshift

Body:
This is a very simple pure python app (not Django or Flask).

What is the step-by-step and correct way of deploying this app on Openshift ?, so that it runs forever.

Code:

import requests as rq
from bs4 import BeautifulSoup as bs
import time
url = "https://apod.nasa.gov/apod/astropix.html"
page = rq.get(url).content
soup = bs(page, 'html.parser')
response = soup.find('img')
if response == None:
    imglink = soup.find('iframe')['src']
else:
    imglink = 'https://apod.nasa.gov/apod/' + response['src']
def main():
    while True:
        sess = rq.Session()
        cid='@*********'
        turl = 'https://api.telegram.org/bot****************/'
        if response == None:
            imglink = soup.find('iframe')['src']
            params = {'chat_id':cid,'text':imglink}
            sess.post(turl + 'sendMessage', data=params)
        else:
            imglink = 'https://apod.nasa.gov/apod/' + response['src']
            title = soup.find('b').get_text()
            params = {'chat_id':cid,'photo':imglink,'caption':title}
            sess.post(turl + 'sendPhoto', data=params)
        time.sleep(30)
if __name__ == '__main__':
    main()


问:
Understanding UIViewRepresentable
Swift 5.0 iOS 13

Trying to understand how UIViewRepresentable works, and put together this simple example, almost there, but maybe its complete nonsense. Yes, I know there is already a tapGesture in SwiftUI, this is just a test.

Won't compile cause it says 'super.init' isn't called on all paths before returning from initialiser, which I try and set but obviously not correctly.

```<code>import SwiftUI

struct newView: UIViewRepresentable {

typealias UIViewType = UIView
var v = UIView()

func updateUIView(_ uiView: UIView, context: Context) {
  v.backgroundColor = UIColor.yellow
}

func makeUIView(context: Context) -> UIView {
  let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}

func makeCoordinator() -> newView.Coordinator {
  Coordinator(v)
}

final class Coordinator: UIView {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

required init?(coder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

@objc func handleTap(sender: UITapGestureRecognizer) {
    print("tap")
  }
 }

}
</code>```

答:
Thats because your Coordinator is a subclass of the UIView and you

Must call a designated initializer of the superclass 'UIView'

before returning from the init:

```<code>init(_ view: UIView) {
    self.view = view
    super.init(frame: .zero) // Or any other frame you need
}
</code>```

Title: Understanding UIViewRepresentable

Body:
Swift 5.0 iOS 13

Trying to understand how UIViewRepresentable works, and put together this simple example, almost there, but maybe its complete nonsense. Yes, I know there is already a tapGesture in SwiftUI, this is just a test.

Won't compile cause it says 'super.init' isn't called on all paths before returning from initialiser, which I try and set but obviously not correctly.

import SwiftUI

struct newView: UIViewRepresentable {

typealias UIViewType = UIView
var v = UIView()

func updateUIView(_ uiView: UIView, context: Context) {
  v.backgroundColor = UIColor.yellow
}

func makeUIView(context: Context) -> UIView {
  let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}

func makeCoordinator() -> newView.Coordinator {
  Coordinator(v)
}

final class Coordinator: UIView {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

required init?(coder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

@objc func handleTap(sender: UITapGestureRecognizer) {
    print("tap")
  }
 }

}

Body:
Thats because your Coordinator is a subclass of the UIView and you

Must call a designated initializer of the superclass 'UIView'

before returning from the init:

init(_ view: UIView) {
    self.view = view
    super.init(frame: .zero) // Or any other frame you need
}


问:
Build fails with Nuget package errors when solution is build in Azure Dev ops
We have recently decided to Implement CICD in the project ,using Azure Dev ops. We use TFS for the code check in and have the code repository in Azure Dev Ops.
Attaching the configurations we made for the project in Dev Ops pipeline.

答:
In your logs I can see you target an older version of nuget.org

```<code>https://api.nuget.org/v2
</code>```

you should go instead to

```<code>https://api.nuget.org/v3/index.json
</code>```

But there is no need to use command line to restore your nugets, you can use the restore task instead.

Do not forget to add any private nuget feeds if you have one.

Body:
In your logs I can see you target an older version of nuget.org

https://api.nuget.org/v2

you should go instead to

https://api.nuget.org/v3/index.json

But there is no need to use command line to restore your nugets, you can use the restore task instead.

Do not forget to add any private nuget feeds if you have one.


问:
How to get Select-Object to return a raw type (e.g. String) rather than PSCustomObject?
The following code gives me an array of PSCustomObjects, how can I get it to return an array of Strings?

```<code>$files = Get-ChildItem $directory -Recurse | Select-Object FullName | Where-Object {!($_.psiscontainer)}
</code>```

(As a secondary question, what's the psiscontainer part for? I copied that from an example online)

Post-Accept Edit: Two great answers, wish I could mark both of them. Have awarded the original answer.

答:
To get the string for the file name you can use

```<code>$files = Get-ChildItem $directory -Recurse | Where-Object {!($_.psiscontainer)} | Select-Object -ExpandProperty FullName
</code>```

The -ExpandProperty parameter allows you to get back an object based on the type of the property specified.

Further testing shows that this did not work with V1, but that functionality is fixed as of the V2 CTP3.

OwnerDisplayName: Mark Ingram

ContentLicense: CC BY-SA 2.5

Body:
The following code gives me an array of PSCustomObjects, how can I get it to return an array of Strings?

$files = Get-ChildItem $directory -Recurse | Select-Object FullName | Where-Object {!($_.psiscontainer)}

(As a secondary question, what's the psiscontainer part for? I copied that from an example online)

Post-Accept Edit: Two great answers, wish I could mark both of them. Have awarded the original answer.

LastEditorDisplayName: Sung Meister

Body:
To get the string for the file name you can use

$files = Get-ChildItem $directory -Recurse | Where-Object {!($_.psiscontainer)} | Select-Object -ExpandProperty FullName

The -ExpandProperty parameter allows you to get back an object based on the type of the property specified.

Further testing shows that this did not work with V1, but that functionality is fixed as of the V2 CTP3.

OwnerDisplayName: Steven Murawski

LastEditorDisplayName: Steven Murawski


问:
Remove the double quotes from a float in a dataframe
I have some options chain data:

```<code>Contract Name,Last Trade Date,Strike,Last Price,Bid,Ask,Change

AMZN200605P03320000,2020-05-28 3:24PM EDT,3320.0,900.65,876.0,893.5,+900.65

AMZN200605P03500000,2020-05-28 3:51PM EDT,3500.0,1099.55,1055.5,1073.5,"+1,099.55"
</code>```

The entry - "+1,099.55" seems to be a bad entry in the data, since there are not any other records like that and I need to sanitize it before inserting into a SQLDB. I have tried a couple different things but none have worked. Any insight would be greatly appreciated:

```<code>optionsChainPuts['Change'] = optionsChainPuts['Change'].map(lambda x: x.lstrip('\"+').rstrip('\"'))
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).str.replace('\D', '')
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).map(lambda x: x.replace('"', ''))
</code>```

Thank you

答:
Issues is numbers with commas and quotes.

Use locale to convert from European to English

Code

```<code>from io import StringIO
import pandas as pd
import locale

s = '''Contract Name,Last Trade Date,Strike,Last Price,Bid,Ask,Change
AMZN200605P03320000,2020-05-28 3:24PM EDT,3320.0,900.65,876.0,893.5,+900.65
AMZN200605P03500000,2020-05-28 3:51PM EDT,3500.0,1099.55,1055.5,1073.5,"+1,099.55"'''

df = pd.read_csv(StringIO(s))

# set local to English
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )

# Convert column to float
df['Change'] = df['Change'].apply(lambda x: locale.atof(x))

print(df['Change'])
</code>```

Output

```<code>Name: Change, dtype: object
0     900.65
1    1099.55
Name: Change, dtype: float64
</code>```

Body:
I have some options chain data:

Contract Name,Last Trade Date,Strike,Last Price,Bid,Ask,Change

AMZN200605P03320000,2020-05-28 3:24PM EDT,3320.0,900.65,876.0,893.5,+900.65

AMZN200605P03500000,2020-05-28 3:51PM EDT,3500.0,1099.55,1055.5,1073.5,"+1,099.55"

The entry - "+1,099.55" seems to be a bad entry in the data, since there are not any other records like that and I need to sanitize it before inserting into a SQLDB. I have tried a couple different things but none have worked. Any insight would be greatly appreciated:

optionsChainPuts['Change'] = optionsChainPuts['Change'].map(lambda x: x.lstrip('\"+').rstrip('\"'))
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).str.replace('\D', '')
optionsChainPuts['Change'] = optionsChainPuts['Change'].astype(str).map(lambda x: x.replace('"', ''))

Thank you

Body:
Issues is numbers with commas and quotes.

Use locale to convert from European to English

Code

from io import StringIO
import pandas as pd
import locale

s = '''Contract Name,Last Trade Date,Strike,Last Price,Bid,Ask,Change
AMZN200605P03320000,2020-05-28 3:24PM EDT,3320.0,900.65,876.0,893.5,+900.65
AMZN200605P03500000,2020-05-28 3:51PM EDT,3500.0,1099.55,1055.5,1073.5,"+1,099.55"'''

df = pd.read_csv(StringIO(s))

# set local to English
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )

# Convert column to float
df['Change'] = df['Change'].apply(lambda x: locale.atof(x))

print(df['Change'])

Output

Name: Change, dtype: object
0     900.65
1    1099.55
Name: Change, dtype: float64


问:
In a bootstrap responsive page how to center a div

I need to create a responsive page using bootstrap by position a div at the centre of a page as like in the below mentioned layout.

答:
In Bootstrap 4, use:

```<code><div class="d-flex justify-content-center">...</div>
</code>```

You can also change the position depending on what you want:

```<code><div class="d-flex justify-content-start">...</div>
<div class="d-flex justify-content-end">...</div>
<div class="d-flex justify-content-between">...</div>
<div class="d-flex justify-content-around">...</div>
</code>```

Reference here

Body:
In Bootstrap 4, use:

<div class="d-flex justify-content-center">...</div>

You can also change the position depending on what you want:

<div class="d-flex justify-content-start">...</div>
<div class="d-flex justify-content-end">...</div>
<div class="d-flex justify-content-between">...</div>
<div class="d-flex justify-content-around">...</div>

Reference here


问:
Paypal payout PHP internal server error when creating new ProductionEnvironment object
I'm trying to integrate PaypalPayoutSDK in my project. I've tried setting up the project like described in the instructions.

Here is what I have:

```<code>use PaypalPayoutsSDK\Core\PayPalHttpClient;
use PaypalPayoutsSDK\Core\ProductionEnvironment;

// Creating an environment
$clientId = "myid";
$clientSecret = "mysecret";

$environment = new ProductionEnvironment($clientId, $clientSecret);
</code>```

And the folder structure is just:

```<code>-payment
  -myfile.php
  -PaypalPayoutsSDK
</code>```

When I try to use  new ProductionEnvironment() I get an 500 Internal Server Error I'm not very adept in PHP so I might not easily understand what's going on an how to fix it. For example I'm not using composer and I probably won't be able to unless it is absolutely necessary to get this to work. My project is purely PHP without anything added to it.

Here is the error message I get:

```<code>Fatal error: Uncaught Error: Class 'PaypalPayoutsSDK\Core\ProductionEnvironment' not found in /hermes/bosnaweb27a/b1507/dom.mynamestudios/myname/payment/payuser.php:14 Stack trace: #0 {main} thrown in /hermes/bosnaweb27a/b1507/dom.mynamestudios/myname/payment/payuser.php on line 14
</code>```

What could be the problem here? And how can I fix it?

答:
If you add things like:

```<code>ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
</code>```

To the top of your PHP file, you may get a more meaningful error message

Body:
I'm trying to integrate PaypalPayoutSDK in my project. I've tried setting up the project like described in the instructions.

Here is what I have:

use PaypalPayoutsSDK\Core\PayPalHttpClient;
use PaypalPayoutsSDK\Core\ProductionEnvironment;

// Creating an environment
$clientId = "myid";
$clientSecret = "mysecret";

$environment = new ProductionEnvironment($clientId, $clientSecret);

And the folder structure is just:

-payment
  -myfile.php
  -PaypalPayoutsSDK

When I try to use  new ProductionEnvironment() I get an 500 Internal Server Error I'm not very adept in PHP so I might not easily understand what's going on an how to fix it. For example I'm not using composer and I probably won't be able to unless it is absolutely necessary to get this to work. My project is purely PHP without anything added to it.

Here is the error message I get:

Fatal error: Uncaught Error: Class 'PaypalPayoutsSDK\Core\ProductionEnvironment' not found in /hermes/bosnaweb27a/b1507/dom.mynamestudios/myname/payment/payuser.php:14 Stack trace: #0 {main} thrown in /hermes/bosnaweb27a/b1507/dom.mynamestudios/myname/payment/payuser.php on line 14

What could be the problem here? And how can I fix it?

Body:
If you add things like:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

To the top of your PHP file, you may get a more meaningful error message


问:
Testcafe aborts with ELIFECYCLE npm error and exit status 4
I know this is the most common issue with Testcafe, but I previously posted questions and solutions doesn't match/work to resolve my issue. Testcafe version 1.8.4, with allure reporting. I have configured few test suites running sequential in my project but, after first suite run Testcafe terminates with the following error and aborts the test run.

```<code>npm ERR! code ELIFECYCLE
npm ERR! errno 4
npm ERR! user-journey-tests@1.0.0 test:appjourneys:azure: `TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure`
npm ERR! Exit status 4
npm ERR!
npm ERR! Failed at the user-journey-tests@1.0.0 test:appjourneys:azure script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/Venkat/.npm/_logs/2020-05-27T03_13_43_108Z-debug.log
Below is the debug log
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/usr/local/Cellar/node/12.10.0/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'test:appjourneys:azure'
1 verbose cli ]
2 info using npm@6.11.3
3 info using node@v12.10.0
4 verbose run-script [
4 verbose run-script   'pretest:appjourneys:azure',
4 verbose run-script   'test:appjourneys:azure',
4 verbose run-script   'posttest:appjourneys:azure'
4 verbose run-script ]
5 info lifecycle user-journey-tests@1.0.0~pretest:appjourneys:azure: user-journey-tests@1.0.0
6 info lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: user-journey-tests@1.0.0
7 verbose lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: unsafe-perm in lifecycle true
8 verbose lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/Venkat/GAP/store-service/user-journeys-testcafe/node_modules/.bin:/usr/local/Cellar/maven/3.6.0/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/Cellar/maven/3.6.0/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin
9 verbose lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: CWD: /Users/Venkat/GAP/store-service/user-journeys-testcafe
10 silly lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: Args: [
10 silly lifecycle   '-c',
10 silly lifecycle   "TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure"
10 silly lifecycle ]
11 silly lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: Returned: code: 4  signal: null
12 info lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: Failed to exec test:appjourneys:azure script
13 verbose stack Error: user-journey-tests@1.0.0 test:appjourneys:azure: `TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure`
13 verbose stack Exit status 4
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:209:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:209:13)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid user-journey-tests@1.0.0
15 verbose cwd /Users/Venkat/GAP/store-service/user-journeys-testcafe
16 verbose Darwin 17.7.0
17 verbose argv "/usr/local/Cellar/node/12.10.0/bin/node" "/usr/local/bin/npm" "run" "test:appjourneys:azure"
18 verbose node v12.10.0
19 verbose npm  v6.11.3
20 error code ELIFECYCLE
21 error errno 4
22 error user-journey-tests@1.0.0 test:appjourneys:azure: `TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure`
22 error Exit status 4
23 error Failed at the user-journey-tests@1.0.0 test:appjourneys:azure script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 4, true ]
</code>```

I tried the following:

npm -clean install

update testcafe to latest version 1.8.4 3.

I merged my suite in to one single npm run <cmd> - This helps to run the tests but still the error continues to show up at the end and build status is unstable. Any thoughts how to over come this?

答:
I see the following error in the NPM log:

```<code>Error: user-journey-tests@1.0.0 test:appjourneys:azure: \\`TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure\\`
Exit status 4
     at EventEmitter.<anonymous>
</code>```

It means that TestCafe finished tests with exit code 4.

TestCafe finishes with a non-zero exit code when some tests fail during your test session. In this particular case, 4 tests failed.

If you want to disable test failure indication via exit codes, you can append || exit 0 to the TestCafe command.

Body:
I know this is the most common issue with Testcafe, but I previously posted questions and solutions doesn't match/work to resolve my issue. Testcafe version 1.8.4, with allure reporting. I have configured few test suites running sequential in my project but, after first suite run Testcafe terminates with the following error and aborts the test run.

npm ERR! code ELIFECYCLE
npm ERR! errno 4
npm ERR! user-journey-tests@1.0.0 test:appjourneys:azure: `TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure`
npm ERR! Exit status 4
npm ERR!
npm ERR! Failed at the user-journey-tests@1.0.0 test:appjourneys:azure script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/Venkat/.npm/_logs/2020-05-27T03_13_43_108Z-debug.log
Below is the debug log
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/usr/local/Cellar/node/12.10.0/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'test:appjourneys:azure'
1 verbose cli ]
2 info using npm@6.11.3
3 info using node@v12.10.0
4 verbose run-script [
4 verbose run-script   'pretest:appjourneys:azure',
4 verbose run-script   'test:appjourneys:azure',
4 verbose run-script   'posttest:appjourneys:azure'
4 verbose run-script ]
5 info lifecycle user-journey-tests@1.0.0~pretest:appjourneys:azure: user-journey-tests@1.0.0
6 info lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: user-journey-tests@1.0.0
7 verbose lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: unsafe-perm in lifecycle true
8 verbose lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/Venkat/GAP/store-service/user-journeys-testcafe/node_modules/.bin:/usr/local/Cellar/maven/3.6.0/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/Cellar/maven/3.6.0/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin
9 verbose lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: CWD: /Users/Venkat/GAP/store-service/user-journeys-testcafe
10 silly lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: Args: [
10 silly lifecycle   '-c',
10 silly lifecycle   "TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure"
10 silly lifecycle ]
11 silly lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: Returned: code: 4  signal: null
12 info lifecycle user-journey-tests@1.0.0~test:appjourneys:azure: Failed to exec test:appjourneys:azure script
13 verbose stack Error: user-journey-tests@1.0.0 test:appjourneys:azure: `TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure`
13 verbose stack Exit status 4
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:209:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:209:13)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid user-journey-tests@1.0.0
15 verbose cwd /Users/Venkat/GAP/store-service/user-journeys-testcafe
16 verbose Darwin 17.7.0
17 verbose argv "/usr/local/Cellar/node/12.10.0/bin/node" "/usr/local/bin/npm" "run" "test:appjourneys:azure"
18 verbose node v12.10.0
19 verbose npm  v6.11.3
20 error code ELIFECYCLE
21 error errno 4
22 error user-journey-tests@1.0.0 test:appjourneys:azure: `TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure`
22 error Exit status 4
23 error Failed at the user-journey-tests@1.0.0 test:appjourneys:azure script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 4, true ]

I tried the following:

npm -clean install

update testcafe to latest version 1.8.4 3.

I merged my suite in to one single npm run <cmd> - This helps to run the tests but still the error continues to show up at the end and build status is unstable. Any thoughts how to over come this?

Body:
I see the following error in the NPM log:

Error: user-journey-tests@1.0.0 test:appjourneys:azure: \\`TARGET_ENV=test DATA_CENTER=azwus2 testcafe 'chromium:headless:emulation' './journeys/app-journeys/*-spec.js' -r allure\\`
Exit status 4
     at EventEmitter.<anonymous>

It means that TestCafe finished tests with exit code 4.

TestCafe finishes with a non-zero exit code when some tests fail during your test session. In this particular case, 4 tests failed.

If you want to disable test failure indication via exit codes, you can append || exit 0 to the TestCafe command.


问:
Any way to get VS to recognise ReSharper razor errors and fail compilation
Is there any way to do this? The razor support in ReSharper 6 is excellent, and it would be nice for the compiler to recognise razor view errors as compile time errors.</p>

答:
Currently, there is no way treat ReSharper errors as compile errors.
But you can enable Solution Wide Analysis and will be informed if there are any errors in solution from ReSharper.
Also, you can enable own Microsoft analysis of views during build time - look at this article http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx</p>


问:
Two Dependent Combo Boxes

**Edit:** Managed to find the solution to it thanks to fellow user @Tin Bum

I'm trying to make 2 Combo Box where the the first one (Cmb1) will show only unique values from Column 1 and then (Cmb2) will show a list of values from Column 2 that are related to Column 1.

Populating the Cmb1 has been successful however the problem lies with populating Cmb2.
```<code>Column 1    Column 2
1             a
1             b
1             c
2             d
2             e
</code>```

The problem lies with populating Cmb2

```<code>Private Sub UserForm_Activate()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")
With wslk
t1 = .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).row

On Error Resume Next
For y = 2 To t1
Set c = .Cells(y, 2)
Set t1rng = .Range(.Cells(2, 2), .Cells(y, 2))
x = Application.WorksheetFunction.CountIf(t1rng, c)
If x = 1 Then Cmb1.AddItem c
Next y
On Error GoTo 0
End With

End Sub

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Cmb2.ListIndex = -1
If Cmb1.ListIndex > -1 Then
'Currently I am stuck over here
Cmb2.List =

**Solution:**
Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If

End If
End Sub
</code>```

答:
This the bones of a solution for the Exit Event Code.
It should be Ok for hundreds of rows but may be slow for thousands of rows, also you still have to workout the 2 ranges - I've arbitrarily assigned them to fixed ranges.

On the plus side it should be simple to follow

```<code>Dim Rng1 As Range, Rng2 As Range
Dim xCel As Range, List2 As String

Rng1 = Range("A10:A20") ' whatever Range covers your Col1 Data
Rng2 = Range("B10:B20") ' whatever Range covers your Col2 Data

List2 = ""
For Each xCel In Rng2.Cells
   If xCel.Offset(0, -1).Value = Combobox1.Value Then
      ' Add this Value to a String using VbCrLf as a Separator
      List2 = IIf(List2 = "", "", List2 & vbCrLf) & CStr(xCel.Value)
   End If
Next xCel
' Split the String into an Array of Values for ComboBox2
ComboBox2.List = Split(List2, vbCrLf)
</code>```

It also relies on NOT HAVING CHR(13) & CHR(10) (VbCrLF) in your data

Title: Two Dependent Combo Boxes

Body:
**Edit:** Managed to find the solution to it thanks to fellow user @Tin Bum

I'm trying to make 2 Combo Box where the the first one (Cmb1) will show only unique values from Column 1 and then (Cmb2) will show a list of values from Column 2 that are related to Column 1.

Populating the Cmb1 has been successful however the problem lies with populating Cmb2.

Column 1    Column 2
1             a
1             b
1             c
2             d
2             e

The problem lies with populating Cmb2

Private Sub UserForm_Activate()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")
With wslk
t1 = .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).row

On Error Resume Next
For y = 2 To t1
Set c = .Cells(y, 2)
Set t1rng = .Range(.Cells(2, 2), .Cells(y, 2))
x = Application.WorksheetFunction.CountIf(t1rng, c)
If x = 1 Then Cmb1.AddItem c
Next y
On Error GoTo 0
End With

End Sub

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Cmb2.ListIndex = -1
If Cmb1.ListIndex > -1 Then
'Currently I am stuck over here
Cmb2.List =

**Solution:**
Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If

End If
End Sub

Body:
This the bones of a solution for the Exit Event Code.
It should be Ok for hundreds of rows but may be slow for thousands of rows, also you still have to workout the 2 ranges - I've arbitrarily assigned them to fixed ranges.

On the plus side it should be simple to follow

Dim Rng1 As Range, Rng2 As Range
Dim xCel As Range, List2 As String

Rng1 = Range("A10:A20") ' whatever Range covers your Col1 Data
Rng2 = Range("B10:B20") ' whatever Range covers your Col2 Data

List2 = ""
For Each xCel In Rng2.Cells
   If xCel.Offset(0, -1).Value = Combobox1.Value Then
      ' Add this Value to a String using VbCrLf as a Separator
      List2 = IIf(List2 = "", "", List2 & vbCrLf) & CStr(xCel.Value)
   End If
Next xCel
' Split the String into an Array of Values for ComboBox2
ComboBox2.List = Split(List2, vbCrLf)

It also relies on NOT HAVING CHR(13) & CHR(10) (VbCrLF) in your data


问:
dynamically changing classes in Gatsby
I am going through this little tutorial the guy is using Vue and I have never dynamically changed classes in React before.  I am trying to replicate this:

```<code>    <div :class="isOpen ? 'block' : 'hidden'" class="px-2 pt-2 pb-4">
      <a href="#" class="block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800">List your property</a>
      <a href="#" class="mt-1 block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800">Trips</a>
      <a href="#" class="mt-1 block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800">Messages</a>
    </div>
  </header>
</template>

<script>
export default {
  data() {
    return {
      isOpen: false,
    }
  },
}
</script>
</code>```

This is the component I am trying to achieve it on.

```<code>const Nav = () => {
    const data = useStaticQuery(graphql`
        query {
            site {
                siteMetadata {
                    title
                    author
                    social
                }
            }
        }
    `)

    return (
        <header className="bg-gray-900">
            <div className="flex items-center justify-between px-4 py-3 mb-4s">
                <div>
                    <h1 className="mb-0 text-2xl">
                        <Link to="/">
                            {data.site.siteMetadata.social}
                        </Link>
                    </h1>
                </div>
                <div>
                    <button type="button" className="block text-gray-500 hover:text-white focus:text-white focus:outline-none">
                    <svg class="h-6 w-6 fill-current" viewBox="0 0 24 24">
                        <path fill-rule="evenodd" d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z"/>
                    </svg>
                    </button>
                </div>
            </div>

            <div className="px-2 pt-2 pb-4">
                <Link
                    className="block px-2 py-1 rounded hover:bg-gray-800"
                    activeClassName=""
                >
                    Open Source
                </Link>
                <Link
                    className="mt-1 block px-2 py-1 rounded hover:bg-gray-800"
                    activeClassName=""
                    to="/posts"
                >
                    Posts
                </Link>
                <Link
                    className="mt-1 block px-2 py-1 rounded hover:bg-gray-800"
                    activeClassName=""
                    to="/contact"
                >
                    Contact
                </Link>
            </div>

        </header>
    )
}
</code>```

I have tried a few things but as I am pretty new to react and new to the way things are done I am little lost.

any pointers would be good.

答:
It is simple as using a simple ternary. For example, you want to toggle between
className 'red' and 'green'  based on the value of variable isOpen,

// assume some variable isOpen is a boolean value which will be set dynamically

const myClassName = isOpen ? 'green' : 'red';

// in your component the set the className prop to the className you created
return (

    my dynamic element

)
```

<p>You can also do that in one line</p>

<pre class="lang-js prettyprint-override"><code>// in your component

return (
  <div className={isOpen ? 'green' : 'red'}>
   my dynamic element
  </div>
)
</code>```

Here is a codesandbox example.

Also, let's say you want an existing CSS class name to merge with another className depending on the value of a variable.

// let's say you want to add 'color-green' depending on variable isOpen with
// an existing class of 'flex-container'

const existingCls = 'flex-container'

const myClassName = isOpen ? `${existingCls} color-green` : existingCls

```

Title: dynamically changing classes in Gatsby

Body:
I am going through this little tutorial the guy is using Vue and I have never dynamically changed classes in React before.  I am trying to replicate this:

      List your property
      Trips
      Messages

</template>

This is the component I am trying to achieve it on.

const Nav = () => {
    const data = useStaticQuery(graphql`
        query {
            site {
                siteMetadata {
                    title
                    author
                    social
                }
            }
        }
    `)

    return (

                        <Link to="/">
                            {data.site.siteMetadata.social}
                        </Link>

                    <button type="button" className="block text-gray-500 hover:text-white focus:text-white focus:outline-none">
                    <svg class="h-6 w-6 fill-current" viewBox="0 0 24 24">
                        <path fill-rule="evenodd" d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z"/>
                    </svg>
                    </button>

                <Link
                    className="block px-2 py-1 rounded hover:bg-gray-800"
                    activeClassName=""
                >
                    Open Source
                </Link>
                <Link
                    className="mt-1 block px-2 py-1 rounded hover:bg-gray-800"
                    activeClassName=""
                    to="/posts"
                >
                    Posts
                </Link>
                <Link
                    className="mt-1 block px-2 py-1 rounded hover:bg-gray-800"
                    activeClassName=""
                    to="/contact"
                >
                    Contact
                </Link>

    )
}

I have tried a few things but as I am pretty new to react and new to the way things are done I am little lost.

any pointers would be good.

Body:
It is simple as using a simple ternary. For example, you want to toggle between
className 'red' and 'green'  based on the value of variable isOpen,

// assume some variable isOpen is a boolean value which will be set dynamically

const myClassName = isOpen ? 'green' : 'red';

// in your component the set the className prop to the className you created
return (
  <div className={myClassName}>
    my dynamic element
  </div>
)

You can also do that in one line

// in your component

return (
  <div className={isOpen ? 'green' : 'red'}>
   my dynamic element
  </div>
)

Here is a codesandbox example.

Also, let's say you want an existing CSS class name to merge with another className depending on the value of a variable.

// let's say you want to add 'color-green' depending on variable isOpen with
// an existing class of 'flex-container'

const existingCls = 'flex-container'

const myClassName = isOpen ? `${existingCls} color-green` : existingCls


问:
How to keep object of subclass in another class in cpp? Base class undefined error
I'm coding simple shop program in cpp. I have 3 classes: Shop, Client, Bucket. Shop is parent class for Bucket. Shop has vector of clients and every client has his own bucket.
I've got problem with #include's. I have to include Client.h in Shop.h so the Shop could see the vector of clients, but it seems I also have to include Bucket.h in Clinet.h for similar reason.
This generates a problem: Bucket is being included before Shop so I get 'Base Class Undefined' error.
How can I make this work?

Shop.h

```<code>#pragma once
#include <vector>
#include <string>
#include "functions.h"
#include "Client.h"

class Shop {

protected:
    std::vector<int> quantities;
    std::vector<std::string> products;
    std::vector<float> prices;
private:
    std::vector<Client*> clients;
    int loggedClient;
public:
    Shop();
    ~Shop();
    int readProducts();
    int loadClientsBase();
    int checkLoginData(std::string log, std::string pass, int *logged);
    int checkIfSameLogin(std::string log);
    int addClient();
    void login();
    void logout();
    int sell();
    virtual void display();
    void displayLoggedClient();
    int saveHistory();
};

</code>```

Client.h

```<code>#pragma once
#include "Bucket.h"

class Client
{
private:
    float money=0.0;
    Bucket bucket;
    std::string login;
    std::string password;
    std::string description;
public:
    Client();
    ~Client();
    void addLoginData(std::string log, std::string pass, std::string desc, float mon);
    std::string getLogin() { return login; };
    std::string getPassword() { return password; };
    std::string getDescription() { return description; };
    float getMoney() { return money; };
    void addLogin(std::string log);
    void addPassword(std::string pass);
    void addDescription(std::string desc);
    void addMoney(float m);
    void addToBucket(std::string prod, int quant, float price);
    void displayBucket();
    Bucket getBucket() { return bucket; };

    friend std::ostream& operator<<(std::ostream& os, Client& client);
};
</code>```

Bucket.h

```<code>#pragma once
#include <vector>
#include <string>
#include "Shop.h"

class Bucket : public Shop
{
public:
    Bucket();
    ~Bucket();
    void addProduct(std::string name, int amount, float price);
    void deleteProduct();
    void display();
    std::string getProduct(int i);
    int getQuantity(int i);
    float getPrice(int i);
    int getNumberOfProducts() { return products.size(); };
    void clearBucket();
};
</code>```

答: To solve the immediate issue, you'll need to forward declare Client class in Shop.h. However the class hierarchy you are building here is confusing to say the least, e.g. each Client owns a Shop, changing the class hierarchy to something more sensible should remove the problem altogether.

Body:
I'm coding simple shop program in cpp. I have 3 classes: Shop, Client, Bucket. Shop is parent class for Bucket. Shop has vector of clients and every client has his own bucket.
I've got problem with #include's. I have to include Client.h in Shop.h so the Shop could see the vector of clients, but it seems I also have to include Bucket.h in Clinet.h for similar reason.
This generates a problem: Bucket is being included before Shop so I get 'Base Class Undefined' error.
How can I make this work?

Shop.h

#pragma once
#include <vector>
#include <string>
#include "functions.h"
#include "Client.h"

class Shop {

protected:
    std::vector<int> quantities;
    std::vector<std::string> products;
    std::vector<float> prices;
private:
    std::vector<Client*> clients;
    int loggedClient;
public:
    Shop();
    ~Shop();
    int readProducts();
    int loadClientsBase();
    int checkLoginData(std::string log, std::string pass, int *logged);
    int checkIfSameLogin(std::string log);
    int addClient();
    void login();
    void logout();
    int sell();
    virtual void display();
    void displayLoggedClient();
    int saveHistory();
};

Client.h

#pragma once
#include "Bucket.h"

class Client
{
private:
    float money=0.0;
    Bucket bucket;
    std::string login;
    std::string password;
    std::string description;
public:
    Client();
    ~Client();
    void addLoginData(std::string log, std::string pass, std::string desc, float mon);
    std::string getLogin() { return login; };
    std::string getPassword() { return password; };
    std::string getDescription() { return description; };
    float getMoney() { return money; };
    void addLogin(std::string log);
    void addPassword(std::string pass);
    void addDescription(std::string desc);
    void addMoney(float m);
    void addToBucket(std::string prod, int quant, float price);
    void displayBucket();
    Bucket getBucket() { return bucket; };

    friend std::ostream& operator<<(std::ostream& os, Client& client);
};

Bucket.h

#pragma once
#include <vector>
#include <string>
#include "Shop.h"

class Bucket : public Shop
{
public:
    Bucket();
    ~Bucket();
    void addProduct(std::string name, int amount, float price);
    void deleteProduct();
    void display();
    std::string getProduct(int i);
    int getQuantity(int i);
    float getPrice(int i);
    int getNumberOfProducts() { return products.size(); };
    void clearBucket();
};


问:
Executing a python file via crontabs is resulting in a FileNotFoundError
I have a python script which I want to run on a daily basis. I'm using crontabs for this on my Mac with the following command:

```<code>*/1 * * * * /opt/anaconda3/bin/python *absolute_path*/dynamic_dataset.py
</code>```

It is working fine! But the log shows that I am running into a "FileNotFoundError". I am reading a csv and h5 file in which are not found. How can I make crontab also use these files?

Many thanks in advance!

答:
You don't know in which working folder is executed your program. I recommand using such a line:

*/1 * * * * cd /path/to/your/working/dir && /opt/anaconda3/bin/python dynamic_dataset.py
```

Body:
I have a python script which I want to run on a daily basis. I'm using crontabs for this on my Mac with the following command:

*/1 * * * * /opt/anaconda3/bin/python *absolute_path*/dynamic_dataset.py

It is working fine! But the log shows that I am running into a "FileNotFoundError". I am reading a csv and h5 file in which are not found. How can I make crontab also use these files?

Many thanks in advance!


问:
Is U+0085 NEXT LINE (NEL) deprecated?
There is few information about NEL. I think it was supposed to replace LF and CR LF, but it seems like it wasn't very used.

Is it somehow deprecated and should applications interpret it as a new line?

答:
There are many different code points which can be used as line separators, mostly for legacy reasons. Unicode's design seeks to preserve all information, so text can be roundtrip en- and decoded to/from Unicode without information loss. NEL is/was used in EBCDIC to represent newlines, so it made its way into Unicode as a separate character.

It's not "deprecated" in the sense that it still fulfils the function it was designed for, but you will hardly find it in actual use unless you're dealing with legacy EBCDIC somehow. If you do, you may want to treat it as newline, but many modern systems to date just treat it as whitespace.

The Wikipedia article on NEL has more information.

Title: Is U+0085 NEXT LINE (NEL) deprecated?


问:
Can I create a function that compares numbers of a column to a mean for different columns?
For 6 different columns, I have to change all values to 'high'/'low' depending on whether the values are bigger or smaller than the mean of the column. I wrote a function that checks whether the values in a column are smaller/bigger than the mean, but it is only applicable to one of the columns:

```<code>calc.binary <- function(number){
  number[number > mean(modality$auditory)] <- 'high'
  number[!(number %in% 'high')] <- 'low'
  number
}

modality_bin <- mutate_at(modality, vars(auditory:visual), list(calc.binary))
</code>```

I want to apply this function to all 6 columns at once now (columns auditory to visual), but I know I'd have to change the calc.binary function for that. How do I change my function so that it takes the mean of each column and compares the number in that column to that mean? So I can apply the same function to all columns.

答:
You can use : </p>

```<code>library(dplyr)
modality %>%
    mutate_at(vars(auditory:visual), ~ifelse(. > mean(.), "higher", "lower"))
</code>```

Body:
For 6 different columns, I have to change all values to 'high'/'low' depending on whether the values are bigger or smaller than the mean of the column. I wrote a function that checks whether the values in a column are smaller/bigger than the mean, but it is only applicable to one of the columns:

calc.binary <- function(number){
  number[number > mean(modality$auditory)] <- 'high'
  number[!(number %in% 'high')] <- 'low'
  number
}

modality_bin <- mutate_at(modality, vars(auditory:visual), list(calc.binary))

I want to apply this function to all 6 columns at once now (columns auditory to visual), but I know I'd have to change the calc.binary function for that. How do I change my function so that it takes the mean of each column and compares the number in that column to that mean? So I can apply the same function to all columns.

Body:
You can use :

library(dplyr)
modality %>%
    mutate_at(vars(auditory:visual), ~ifelse(. > mean(.), "higher", "lower"))


答:
You should be able to use the apply function in Base-R

```<code>apply(modality[,c(2:5)], 2,function(x) ifelse(x > mean(x),'high','low'))
</code>```

Where modality[,c(2:5,8)] is the data you pass into the function, so chose the columns you want by changing the values in c(2:5,8). If you would like it done on every column then apply(modality, ... would suffice.

Here apply(  ,2 , ) the 2 indicates that we want to run our function column-by-column. 1 would mean row-by-row.

Title: Can I create a function that compares numbers of a column to a mean for different columns?

Body:
You should be able to use the apply function in Base-R

apply(modality[,c(2:5)], 2,function(x) ifelse(x > mean(x),'high','low'))

Where modality[,c(2:5,8)] is the data you pass into the function, so chose the columns you want by changing the values in c(2:5,8). If you would like it done on every column then apply(modality, ... would suffice.

Here apply(  ,2 , ) the 2 indicates that we want to run our function column-by-column. 1 would mean row-by-row.