text:
Q: Start SQS celery worker on Elastic Beanstalk I am trying to start a celery worker on EB but get an error which doesn't explain much.
Command in config file in .ebextensions dir:
03_celery_worker:
  command: "celery worker --app=config --loglevel=info -E --workdir=/opt/python/current/app/my_project/"

The listed command works fine on my local machine (just change workdir parameter).
Errors from the EB:

Activity execution failed, because: /opt/python/run/venv/local/lib/python3.6/site-packages/celery/platforms.py:796: RuntimeWarning: You're running the worker with superuser privileges: this is
    absolutely not recommended!

and

Starting new HTTPS connection (1): eu-west-1.queue.amazonaws.com
     (ElasticBeanstalk::ExternalInvocationError)

I have updated celery worker command with parameter --uid=2 and privileges error disappeared but command execution is still failed due to

ExternalInvocationError

Any suggestions what I do wrong?

A:
ExternalInvocationError

As I understand it means that listed command cannot be run from EB container commands. It is needed to create a script on the server and run celery from the script. This post describes how to do it.
Update:
It is needed to create a config file in .ebextensions directory. I called it celery.config. Link to the post above provides a script which works almost fine. It is needed to make some minor additions to work 100% correct. I had issues with schedule periodic tasks (celery beat). Below are steps on how to fix is:

*

*Install (add to requirements) django-celery beat pip install django-celery-beat, add it to installed apps and use --scheduler parameter when starting celery beat. Instructions are here.

*In the script you specify user which run the script. For celery worker it is celery user which was added earlier in the script (if doesn't exist). When I tried to start celery beat I got error PermissionDenied. It means that celery user doesn't have all necessary rights. using ssh I logged in to EB, looked a list of all users (cat /etc/passwd) and decided to use daemon user.
Listed steps resolved celery beat errors. Updated config file with the script is below (celery.config):
files:
  "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash

      # Create required directories
      sudo mkdir -p /var/log/celery/
      sudo mkdir -p /var/run/celery/

      # Create group called 'celery'
      sudo groupadd -f celery
      # add the user 'celery' if it doesn't exist and add it to the group with same name
      id -u celery &>/dev/null || sudo useradd -g celery celery
      # add permissions to the celery user for r+w to the folders just created
      sudo chown -R celery:celery /var/log/celery/
      sudo chown -R celery:celery /var/run/celery/

      # Get django environment variables
      celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/%/%%/g' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'`
      celeryenv=${celeryenv%?}

      # Create CELERY configuration script
      celeryconf="[program:celeryd]
      directory=/opt/python/current/app
      ; Set full path to celery program if using virtualenv
      command=/opt/python/run/venv/bin/celery worker -A config.celery:app --loglevel=INFO --logfile=\"/var/log/celery/%%n%%I.log\" --pidfile=\"/var/run/celery/%%n.pid\"

      user=celery
      numprocs=1
      stdout_logfile=/var/log/celery-worker.log
      stderr_logfile=/var/log/celery-worker.log
      autostart=true
      autorestart=true
      startsecs=10

      ; Need to wait for currently executing tasks to finish at shutdown.
      ; Increase this if you have very long running tasks.
      stopwaitsecs = 60

      ; When resorting to send SIGKILL to the program to terminate it
      ; send SIGKILL to its whole process group instead,
      ; taking care of its children as well.
      killasgroup=true

      ; if rabbitmq is supervised, set its priority higher
      ; so it starts first
      priority=998

      environment=$celeryenv"

      # Create CELERY BEAT configuraiton script
      celerybeatconf="[program:celerybeat]
      ; Set full path to celery program if using virtualenv
      command=/opt/python/run/venv/bin/celery beat -A config.celery:app --loglevel=INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler --logfile=\"/var/log/celery/celery-beat.log\" --pidfile=\"/var/run/celery/celery-beat.pid\"

      directory=/opt/python/current/app
      user=daemon
      numprocs=1
      stdout_logfile=/var/log/celerybeat.log
      stderr_logfile=/var/log/celerybeat.log
      autostart=true
      autorestart=true
      startsecs=10

      ; Need to wait for currently executing tasks to finish at shutdown.
      ; Increase this if you have very long running tasks.
      stopwaitsecs = 60

      ; When resorting to send SIGKILL to the program to terminate it
      ; send SIGKILL to its whole process group instead,
      ; taking care of its children as well.
      killasgroup=true

      ; if rabbitmq is supervised, set its priority higher
      ; so it starts first
      priority=999

      environment=$celeryenv"

      # Create the celery supervisord conf script
      echo "$celeryconf" | tee /opt/python/etc/celery.conf
      echo "$celerybeatconf" | tee /opt/python/etc/celerybeat.conf

      # Add configuration script to supervisord conf (if not there already)
      if ! grep -Fxq "celery.conf" /opt/python/etc/supervisord.conf
        then
          echo "[include]" | tee -a /opt/python/etc/supervisord.conf
          echo "files: uwsgi.conf celery.conf celerybeat.conf" | tee -a /opt/python/etc/supervisord.conf
      fi

      # Enable supervisor to listen for HTTP/XML-RPC requests.
      # supervisorctl will use XML-RPC to communicate with supervisord over port 9001.
      # Source: https://askubuntu.com/questions/911994/supervisorctl-3-3-1-http-localhost9001-refused-connection
      if ! grep -Fxq "[inet_http_server]" /opt/python/etc/supervisord.conf
        then
          echo "[inet_http_server]" | tee -a /opt/python/etc/supervisord.conf
          echo "port = 127.0.0.1:9001" | tee -a /opt/python/etc/supervisord.conf
      fi

      # Reread the supervisord config
      supervisorctl -c /opt/python/etc/supervisord.conf reread

      # Update supervisord in cache without restarting all services
      supervisorctl -c /opt/python/etc/supervisord.conf update

      # Start/Restart celeryd through supervisord
      supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd
      supervisorctl -c /opt/python/etc/supervisord.conf restart celerybeat

    commands:
      01_killotherbeats:
        command: "ps auxww | grep 'celery beat' | awk '{print $2}' | sudo xargs kill -9 || true"
        ignoreErrors: true
      02_restartbeat:
        command: "supervisorctl -c /opt/python/etc/supervisord.conf restart celerybeat"
        leader_only: true

One thing to focus attention on: in my project celery.py file is in the config directory, that is why I write -A config.celery:app when start celery worker and celery beat


text:
Q: What is the best algorithm for overriding GetHashCode? In .NET, the GetHashCode method is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.
Is there a standard algorithm or best practice on how to implement GetHashCode for my custom classes so I don't degrade performance?

A: Here is my simplistic approach. I am using the classic builder pattern for this. It is typesafe (no boxing/unboxing) and also compatbile with .NET 2.0 (no extension methods etc.).
It is used like this:
public override int GetHashCode()
{
    HashBuilder b = new HashBuilder();
    b.AddItems(this.member1, this.member2, this.member3);
    return b.Result;
}

And here is the acutal builder class:
internal class HashBuilder
{
    private const int Prime1 = 17;
    private const int Prime2 = 23;
    private int result = Prime1;

    public HashBuilder()
    {
    }

    public HashBuilder(int startHash)
    {
        this.result = startHash;
    }

    public int Result
    {
        get
        {
            return this.result;
        }
    }

    public void AddItem<T>(T item)
    {
        unchecked
        {
            this.result = this.result * Prime2 + item.GetHashCode();
        }
    }

    public void AddItems<T1, T2>(T1 item1, T2 item2)
    {
        this.AddItem(item1);
        this.AddItem(item2);
    }

    public void AddItems<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
    }

    public void AddItems<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3,
        T4 item4)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
    }

    public void AddItems<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3,
        T4 item4, T5 item5)
    {
        this.AddItem(item1);
        this.AddItem(item2);
        this.AddItem(item3);
        this.AddItem(item4);
        this.AddItem(item5);
    }

    public void AddItems<T>(params T[] items)
    {
        foreach (T item in items)
        {
            this.AddItem(item);
        }
    }
}

A: I have a Hashing class in Helper library that I use it for this purpose.
/// <summary>
/// This is a simple hashing function from Robert Sedgwicks Hashing in C book.
/// Also, some simple optimizations to the algorithm in order to speed up
/// its hashing process have been added. from: www.partow.net
/// </summary>
/// <param name="input">array of objects, parameters combination that you need
/// to get a unique hash code for them</param>
/// <returns>Hash code</returns>
public static int RSHash(params object[] input)
{
    const int b = 378551;
    int a = 63689;
    int hash = 0;

    // If it overflows then just wrap around
    unchecked
    {
        for (int i = 0; i < input.Length; i++)
        {
            if (input[i] != null)
            {
                hash = hash * a + input[i].GetHashCode();
                a = a * b;
            }
        }
    }

    return hash;
}

Then, simply you can use it as:
public override int GetHashCode()
{
    return Hashing.RSHash(_field1, _field2, _field3);
}

I didn't assess its performance, so any feedback is welcomed.

A: ReSharper users can generate GetHashCode, Equals, and others with ReSharper -> Edit -> Generate Code -> Equality Members.
// ReSharper's GetHashCode looks like this
public override int GetHashCode() {
    unchecked {
        int hashCode = Id;
        hashCode = (hashCode * 397) ^ IntMember;
        hashCode = (hashCode * 397) ^ OtherIntMember;
        hashCode = (hashCode * 397) ^ (RefMember != null ? RefMember.GetHashCode() : 0);
        // ...
        return hashCode;
    }
}

A: If we have no more than 8 properties (hopefully), here is another alternative.
ValueTuple is a struct and appears to have a solid GetHashCode implementation.
That means we could simply do this:
// Yay, no allocations and no custom implementations!
public override int GetHashCode() => (this.PropA, this.PropB).GetHashCode();

Let's take a look at .NET Core's current implementation for ValueTuple's GetHashCode.
This is from ValueTuple:
    internal static int CombineHashCodes(int h1, int h2)
    {
        return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
    }

    internal static int CombineHashCodes(int h1, int h2, int h3)
    {
        return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
    }

And this is from HashHelper:
    public static readonly int RandomSeed = Guid.NewGuid().GetHashCode();

    public static int Combine(int h1, int h2)
    {
        unchecked
        {
            // RyuJIT optimizes this to use the ROL instruction
            // Related GitHub pull request: dotnet/coreclr#1830
            uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
            return ((int)rol5 + h1) ^ h2;
        }
    }

In English:

*

*Left rotate (circular shift) h1 by 5 positions.

*Add the result and h1 together.

*XOR the result with h2.

*Start by performing the above operation on { static random seed, h1 }.

*For each further item, perform the operation on the previous result and the next item (e.g. h2).

It would be nice to know more about the properties of this ROL-5 hash code algorithm.
Regrettably, deferring to ValueTuple for our own GetHashCode may not be as fast as we would like and expect. This comment in a related discussion illustrates that directly calling HashHelpers.Combine is more performant. On the flip side, that one is internal, so we'd have to copy the code, sacrificing much of what we had gained here. Also, we'd be responsible for remembering to first Combine with the random seed. I don't know what the consequences are if we skip that step.

A: Here's my helper class using Jon Skeet's implementation.
public static class HashCode
{
    public const int Start = 17;

    public static int Hash<T>(this int hash, T obj)
    {
        var h = EqualityComparer<T>.Default.GetHashCode(obj);
        return unchecked((hash * 31) + h);
    }
}

Usage:
public override int GetHashCode()
{
    return HashCode.Start
        .Hash(_field1)
        .Hash(_field2)
        .Hash(_field3);
}

If you want to avoid writing an extension method for System.Int32:
public readonly struct HashCode
{
    private readonly int _value;

    public HashCode(int value) => _value = value;

    public static HashCode Start { get; } = new HashCode(17);

    public static implicit operator int(HashCode hash) => hash._value;

    public HashCode Hash<T>(T obj)
    {
        var h = EqualityComparer<T>.Default.GetHashCode(obj);
        return unchecked(new HashCode((_value * 31) + h));
    }

    public override int GetHashCode() => _value;
}

It still avoids any heap allocation and is used exactly the same way:
public override int GetHashCode()
{
    // This time `HashCode.Start` is not an `Int32`, it's a `HashCode` instance.
    // And the result is implicitly converted to `Int32`.
    return HashCode.Start
        .Hash(_field1)
        .Hash(_field2)
        .Hash(_field3);
}

Edit (May 2018): EqualityComparer<T>.Default getter is now a JIT intrinsic - the pull request is mentioned by Stephen Toub in this blog post.

A: ValueTuple - Update for C# 7
As @cactuaroid mentions in the comments, a value tuple can be used. This saves a few keystrokes and more importantly executes purely on the stack (no Garbage):
(PropA, PropB, PropC, PropD).GetHashCode();

(Note: The original technique using anonymous types seems to create an object on the heap, i.e. garbage, since anonymous types are implemented as classes, though this might be optimized out by the compiler. It would be interesting to benchmark these options, but the tuple option should be superior.)
Anonymous Type (Original Answer)
Microsoft already provides a good generic HashCode generator: Just copy your property/field values to an anonymous type and hash it:
new { PropA, PropB, PropC, PropD }.GetHashCode();

This will work for any number of properties. It does not use boxing. It just uses the algorithm already implemented in the framework for anonymous types.

A: Most of my work is done with database connectivity which means that my classes all have a unique identifier from the database.  I always use the ID from the database to generate the hashcode.
// Unique ID from database
private int _id;

...
{
  return _id.GetHashCode();
}

A: In most cases where Equals() compares multiple fields it doesn't really matter if your GetHash() hashes on one field or on many. You just have to make sure that calculating the hash is really cheap (No allocations, please) and fast (No heavy computations and certainly no database connections) and provides a good distribution.
The heavy lifting should be part of the Equals() method; the hash should be a very cheap operation to enable calling Equals() on as few items as possible.
And one final tip: Don't rely on GetHashCode() being stable over multiple aplication runs. Many .Net types don't guarantee their hash codes to stay the same after a restart, so you should only use the value of GetHashCode() for in memory data structures.

A: Pretty much similar to nightcoder's solution except it's easier to raise primes if you want to.
PS: This is one of those times where you puke a little in your mouth, knowing that this could be refactored into one method with 9 default's but it would be slower, so you just close your eyes and try to forget about it.
/// <summary>
/// Try not to look at the source code. It works. Just rely on it.
/// </summary>
public static class HashHelper
{
    private const int PrimeOne = 17;
    private const int PrimeTwo = 23;

    public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();
            hash = hash * PrimeTwo + arg5.GetHashCode();
            hash = hash * PrimeTwo + arg6.GetHashCode();
            hash = hash * PrimeTwo + arg7.GetHashCode();
            hash = hash * PrimeTwo + arg8.GetHashCode();
            hash = hash * PrimeTwo + arg9.GetHashCode();
            hash = hash * PrimeTwo + arg10.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();
            hash = hash * PrimeTwo + arg5.GetHashCode();
            hash = hash * PrimeTwo + arg6.GetHashCode();
            hash = hash * PrimeTwo + arg7.GetHashCode();
            hash = hash * PrimeTwo + arg8.GetHashCode();
            hash = hash * PrimeTwo + arg9.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();
            hash = hash * PrimeTwo + arg5.GetHashCode();
            hash = hash * PrimeTwo + arg6.GetHashCode();
            hash = hash * PrimeTwo + arg7.GetHashCode();
            hash = hash * PrimeTwo + arg8.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();
            hash = hash * PrimeTwo + arg5.GetHashCode();
            hash = hash * PrimeTwo + arg6.GetHashCode();
            hash = hash * PrimeTwo + arg7.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3, T4, T5, T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();
            hash = hash * PrimeTwo + arg5.GetHashCode();
            hash = hash * PrimeTwo + arg6.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();
            hash = hash * PrimeTwo + arg5.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();
            hash = hash * PrimeTwo + arg4.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();
            hash = hash * PrimeTwo + arg3.GetHashCode();

            return hash;
        }
    }

    public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
    {
        unchecked
        {
            int hash = PrimeOne;
            hash = hash * PrimeTwo + arg1.GetHashCode();
            hash = hash * PrimeTwo + arg2.GetHashCode();

            return hash;
        }
    }
}

A: Up until recently my answer would have been very close to Jon Skeet's here. However, I recently started a project which used power-of-two hash tables, that is hash tables where the size of the internal table is 8, 16, 32, etc. There's a good reason for favouring prime-number sizes, but there are some advantages to power-of-two sizes too.
And it pretty much sucked. So after a bit of experimentation and research I started re-hashing my hashes with the following:
public static int ReHash(int source)
{
  unchecked
  {
    ulong c = 0xDEADBEEFDEADBEEF + (ulong)source;
    ulong d = 0xE2ADBEEFDEADBEEF ^ c;
    ulong a = d += c = c << 15 | c >> -15;
    ulong b = a += d = d << 52 | d >> -52;
    c ^= b += a = a << 26 | a >> -26;
    d ^= c += b = b << 51 | b >> -51;
    a ^= d += c = c << 28 | c >> -28;
    b ^= a += d = d << 9 | d >> -9;
    c ^= b += a = a << 47 | a >> -47;
    d ^= c += b << 54 | b >> -54;
    a ^= d += c << 32 | c >> 32;
    a += d << 25 | d >> -25;
    return (int)(a >> 1);
  }
}

And then my power-of-two hash table didn't suck any more.
This disturbed me though, because the above shouldn't work. Or more precisely, it shouldn't work unless the original GetHashCode() was poor in a very particular way.
Re-mixing a hashcode can't improve a great hashcode, because the only possible effect is that we introduce a few more collisions.
Re-mixing a hash code can't improve a terrible hash code, because the only possible effect is we change e.g. a large number of collisions on value 53 to a large number of value 18,3487,291.
Re-mixing a hash code can only improve a hash code that did at least fairly well in avoiding absolute collisions throughout its range (232 possible values) but badly at avoiding collisions when modulo'd down for actual use in a hash table. While the simpler modulo of a power-of-two table made this more apparent, it was also having a negative effect with the more common prime-number tables, that just wasn't as obvious (the extra work in rehashing would outweigh the benefit, but the benefit would still be there).
Edit: I was also using open-addressing, which would also have increased the sensitivity to collision, perhaps more so than the fact it was power-of-two.
And well, it was disturbing how much the string.GetHashCode() implementations in .NET (or study here) could be improved this way (on the order of tests running about 20-30 times faster due to fewer collisions) and more disturbing how much my own hash codes could be improved (much more than that).
All the GetHashCode() implementations I'd coded in the past, and indeed used as the basis of answers on this site, were much worse than I'd throught. Much of the time it was "good enough" for much of the uses, but I wanted something better.
So I put that project to one side (it was a pet project anyway) and started looking at how to produce a good, well-distributed hash code in .NET quickly.
In the end I settled on porting SpookyHash to .NET. Indeed the code above is a fast-path version of using SpookyHash to produce a 32-bit output from a 32-bit input.
Now, SpookyHash is not a nice quick to remember piece of code. My port of it is even less so because I hand-inlined a lot of it for better speed*. But that's what code reuse is for.
Then I put that project to one side, because just as the original project had produced the question of how to produce a better hash code, so that project produced the question of how to produce a better .NET memcpy.
Then I came back, and produced a lot of overloads to easily feed just about all of the native types (except decimal†) into a hash code.
It's fast, for which Bob Jenkins deserves most of the credit because his original code I ported from is faster still, especially on 64-bit machines which the algorithm is optimised for‡.
The full code can be seen at https://bitbucket.org/JonHanna/spookilysharp/src but consider that the code above is a simplified version of it.
However, since it's now already written, one can make use of it more easily:
public override int GetHashCode()
{
  var hash = new SpookyHash();
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

It also takes seed values, so if you need to deal with untrusted input and want to protect against Hash DoS attacks you can set a seed based on uptime or similar, and make the results unpredictable by attackers:
private static long hashSeed0 = Environment.TickCount;
private static long hashSeed1 = DateTime.Now.Ticks;
public override int GetHashCode()
{
  //produce different hashes ever time this application is restarted
  //but remain consistent in each run, so attackers have a harder time
  //DoSing the hash tables.
  var hash = new SpookyHash(hashSeed0, hashSeed1);
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

*A big surprise in this is that hand-inlining a rotation method that returned (x << n) | (x >> -n) improved things. I would have been sure that the jitter would have inlined that for me, but profiling showed otherwise.
†decimal isn't native from the .NET perspective though it is from the C#. The problem with it is that its own GetHashCode() treats precision as significant while its own Equals() does not. Both are valid choices, but not mixed like that. In implementing your own version, you need to choose to do one, or the other, but I can't know which you'd want.
‡By way of comparison. If used on a string, the SpookyHash on 64 bits is considerably faster than string.GetHashCode() on 32 bits which is slightly faster than string.GetHashCode() on 64 bits, which is considerably faster than SpookyHash on 32 bits, though still fast enough to be a reasonable choice.

A: As of https://github.com/dotnet/coreclr/pull/14863, there is a new way to generate hash codes that is super simple! Just write
public override int GetHashCode()
    => HashCode.Combine(field1, field2, field3);

This will generate a quality hash code without you having to worry about the implementation details.

A: Microsoft lead for several way of hashing...
//for classes that contain a single int value
return this.value;

//for classes that contain multiple int value
return x ^ y;

//for classes that contain single number bigger than int
return ((int)value ^ (int)(value >> 32));

//for classes that contain class instance fields which inherit from object
return obj1.GetHashCode();

//for classes that contain multiple class instance fields which inherit from object
return obj1.GetHashCode() ^ obj2.GetHashCode() ^ obj3.GetHashCode();

I can guess that for multiple big int you can use this:
int a=((int)value1 ^ (int)(value1 >> 32));
int b=((int)value2 ^ (int)(value2 >> 32));
int c=((int)value3 ^ (int)(value3 >> 32));
return a ^ b ^ c;

And same for multi-type: all converted first to int using GetHashCode()
then the int values will be xor'ed and the result is your hash.
For those who use hash as ID (I mean an unique value), hash is naturally limited to a number of digits, I think it was 5 bytes for hashing algorithm, at least MD5.
You may turn multiple values to a hashed value and some of them be same, so don't use it as an identifier. (maybe some day I am going to use your component)

A: I usually go with something like the implementation given in Josh Bloch's fabulous Effective Java. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}

As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-FNV example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant is prime though. I don't know quite how important that is.)
This is better than the common practice of XORing hashcodes for two main reasons. Suppose we have a type with two int fields:
XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y

By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.
This page gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The FNV alternative is similarly simple, but uses different constants and XOR instead of ADD as a combining operation. It looks something like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.
// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc, of course :)
        hash = (hash * 16777619) ^ field1.GetHashCode();
        hash = (hash * 16777619) ^ field2.GetHashCode();
        hash = (hash * 16777619) ^ field3.GetHashCode();
        return hash;
    }
}

Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.
As per the documentation:

You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:

*

*You can compute the hash code from fields that are not mutable; or

*You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

The link to the FNV article is broken but here is a copy in the Internet Archive: Eternally Confuzzled - The Art of Hashing

A: Using System.HashCode
If you are using .NET Standard 2.1 or above, you can use the System.HashCode struct. On earlier frameworks it is available from the Microsoft.Bcl.HashCode package. There are two methods of using it:
HashCode.Combine
The Combine method can be used to create a hash code, given up to eight objects.
public override int GetHashCode() => HashCode.Combine(this.object1, this.object2);

HashCode.Add
The Add method helps you to deal with collections:
public override int GetHashCode()
{
    var hashCode = new HashCode();
    hashCode.Add(this.object1);
    foreach (var item in this.collection)
    {
        hashCode.Add(item);
    }
    return hashCode.ToHashCode();
}

GetHashCode Made Easy
An alternative to System.HashCode that is super easy to use while still being fast. You can read the full blog post 'GetHashCode Made Easy' for more details and comments.
Usage Example
public class SuperHero
{
    public int Age { get; set; }
    public string Name { get; set; }
    public List<string> Powers { get; set; }

    public override int GetHashCode() =>
        HashCode.Of(this.Name).And(this.Age).AndEach(this.Powers);
}

Implementation
public struct HashCode : IEquatable<HashCode>
{
    private const int EmptyCollectionPrimeNumber = 19;
    private readonly int value;

    private HashCode(int value) => this.value = value;

    public static implicit operator int(HashCode hashCode) => hashCode.value;

    public static bool operator ==(HashCode left, HashCode right) => left.Equals(right);

    public static bool operator !=(HashCode left, HashCode right) => !(left == right);

    public static HashCode Of<T>(T item) => new HashCode(GetHashCode(item));

    public static HashCode OfEach<T>(IEnumerable<T> items) =>
        items == null ? new HashCode(0) : new HashCode(GetHashCode(items, 0));

    public HashCode And<T>(T item) =>
        new HashCode(CombineHashCodes(this.value, GetHashCode(item)));

    public HashCode AndEach<T>(IEnumerable<T> items)
    {
        if (items == null)
        {
            return new HashCode(this.value);
        }

        return new HashCode(GetHashCode(items, this.value));
    }

    public bool Equals(HashCode other) => this.value.Equals(other.value);

    public override bool Equals(object obj)
    {
        if (obj is HashCode)
        {
            return this.Equals((HashCode)obj);
        }

        return false;
    }

    public override int GetHashCode() => this.value.GetHashCode();

    private static int CombineHashCodes(int h1, int h2)
    {
        unchecked
        {
            // Code copied from System.Tuple a good way to combine hashes.
            return ((h1 << 5) + h1) ^ h2;
        }
    }

    private static int GetHashCode<T>(T item) => item?.GetHashCode() ?? 0;

    private static int GetHashCode<T>(IEnumerable<T> items, int startHashCode)
    {
        var temp = startHashCode;

        var enumerator = items.GetEnumerator();
        if (enumerator.MoveNext())
        {
            temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));

            while (enumerator.MoveNext())
            {
                temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));
            }
        }
        else
        {
            temp = CombineHashCodes(temp, EmptyCollectionPrimeNumber);
        }

        return temp;
    }
}

What Makes a Good Algorithm?
Performance
The algorithm that calculates a hash code needs to be fast. A simple algorithm is usually going to be a faster one. One that does not allocate extra memory will also reduce need for garbage collection, which will in turn also improve performance.
In C# hash functions specifically, you often use the unchecked keyword which stops overflow checking to improve performance.
Deterministic
The hashing algorithm needs to be deterministic i.e. given the same input it must always produce the same output.
Reduce Collisions
The algorithm that calculates a hash code needs to keep hash collisions to a minumum. A hash collision is a situation that occurs when two calls to GetHashCode on two different objects produce identical hash codes. Note that collisions are allowed (some have the misconceptions that they are not) but they should be kept to a minimum.
A lot of hash functions contain magic numbers like 17 or 23. These are special prime numbers which due to their mathematical properties help to reduce hash collisions as compared to using non-prime numbers.
Hash Uniformity
A good hash function should map the expected inputs as evenly as possible over its output range i.e. it should output a wide range of hashes based on its inputs that are evenly spread. It should have hash uniformity.
Prevent's DoS
In .NET Core each time you restart an application you will get different hash codes. This is a security feature to prevent Denial of Service attacks (DoS). For .NET Framework you should enable this feature by adding the following App.config file:
<?xml version ="1.0"?>
<configuration>
   <runtime>
      <UseRandomizedStringHashAlgorithm enabled="1" />
   </runtime>
</configuration>

Because of this feature, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection and they should never be persisted.
Read more about this here.
Cryptographically Secure?
The algorithm does not have to be a Cryptographic hash function. Meaning it does not have to satisfy the following conditions:

*

*It is infeasible to generate a message that yields a given hash value.

*It is infeasible to find two different messages with the same hash value.

*A small change to a message should change the hash value so extensively that the new hash value appears uncorrelated with the old hash value (avalanche effect).

A: This is a good one:
/// <summary>
/// Helper class for generating hash codes suitable
/// for use in hashing algorithms and data structures like a hash table.
/// </summary>
public static class HashCodeHelper
{
    private static int GetHashCodeInternal(int key1, int key2)
    {
        unchecked
        {
           var num = 0x7e53a269;
           num = (-1521134295 * num) + key1;
           num += (num << 10);
           num ^= (num >> 6);

           num = ((-1521134295 * num) + key2);
           num += (num << 10);
           num ^= (num >> 6);

           return num;
        }
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="arr">An array of objects used for generating the
    /// hash code.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data
    /// structures like a hash table.
    /// </returns>
    public static int GetHashCode(params object[] arr)
    {
        int hash = 0;
        foreach (var item in arr)
            hash = GetHashCodeInternal(hash, item.GetHashCode());
        return hash;
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <param name="obj4">The fourth object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and
    /// data structures like a hash table.
    /// </returns>
    public static int GetHashCode<T1, T2, T3, T4>(T1 obj1, T2 obj2, T3 obj3,
        T4 obj4)
    {
        return GetHashCode(obj1, GetHashCode(obj2, obj3, obj4));
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data
    /// structures like a hash table.
    /// </returns>
    public static int GetHashCode<T1, T2, T3>(T1 obj1, T2 obj2, T3 obj3)
    {
        return GetHashCode(obj1, GetHashCode(obj2, obj3));
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data
    /// structures like a hash table.
    /// </returns>
    public static int GetHashCode<T1, T2>(T1 obj1, T2 obj2)
    {
        return GetHashCodeInternal(obj1.GetHashCode(), obj2.GetHashCode());
    }
}

And here is how to use it:
private struct Key
{
    private Type _type;
    private string _field;

    public Type Type { get { return _type; } }
    public string Field { get { return _field; } }

    public Key(Type type, string field)
    {
        _type = type;
        _field = field;
    }

    public override int GetHashCode()
    {
        return HashCodeHelper.GetHashCode(_field, _type);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is Key))
            return false;
        var tf = (Key)obj;
        return tf._field.Equals(_field) && tf._type.Equals(_type);
    }
}

A: Here is my hashcode helper.
It's advantage is that it uses generic type arguments and therefore will not cause boxing:
public static class HashHelper
{
    public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
    {
         unchecked
         {
             return 31 * arg1.GetHashCode() + arg2.GetHashCode();
         }
    }

    public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
    {
        unchecked
        {
            int hash = arg1.GetHashCode();
            hash = 31 * hash + arg2.GetHashCode();
            return 31 * hash + arg3.GetHashCode();
        }
    }

    public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3,
        T4 arg4)
    {
        unchecked
        {
            int hash = arg1.GetHashCode();
            hash = 31 * hash + arg2.GetHashCode();
            hash = 31 * hash + arg3.GetHashCode();
            return 31 * hash + arg4.GetHashCode();
        }
    }

    public static int GetHashCode<T>(T[] list)
    {
        unchecked
        {
            int hash = 0;
            foreach (var item in list)
            {
                hash = 31 * hash + item.GetHashCode();
            }
            return hash;
        }
    }

    public static int GetHashCode<T>(IEnumerable<T> list)
    {
        unchecked
        {
            int hash = 0;
            foreach (var item in list)
            {
                hash = 31 * hash + item.GetHashCode();
            }
            return hash;
        }
    }

    /// <summary>
    /// Gets a hashcode for a collection for that the order of items
    /// does not matter.
    /// So {1, 2, 3} and {3, 2, 1} will get same hash code.
    /// </summary>
    public static int GetHashCodeForOrderNoMatterCollection<T>(
        IEnumerable<T> list)
    {
        unchecked
        {
            int hash = 0;
            int count = 0;
            foreach (var item in list)
            {
                hash += item.GetHashCode();
                count++;
            }
            return 31 * hash + count.GetHashCode();
        }
    }

    /// <summary>
    /// Alternative way to get a hashcode is to use a fluent
    /// interface like this:<br />
    /// return 0.CombineHashCode(field1).CombineHashCode(field2).
    ///     CombineHashCode(field3);
    /// </summary>
    public static int CombineHashCode<T>(this int hashCode, T arg)
    {
        unchecked
        {
            return 31 * hashCode + arg.GetHashCode();
        }
    }

Also it has extension method to provide a fluent interface, so you can use it like this:
public override int GetHashCode()
{
    return HashHelper.GetHashCode(Manufacturer, PartN, Quantity);
}

or like this:
public override int GetHashCode()
{
    return 0.CombineHashCode(Manufacturer)
        .CombineHashCode(PartN)
        .CombineHashCode(Quantity);
}

A: Here is another fluent implementation of the algorithm posted above by Jon Skeet, but which includes no allocations or boxing operations:
public static class Hash
{
    public const int Base = 17;

    public static int HashObject(this int hash, object obj)
    {
        unchecked { return hash * 23 + (obj == null ? 0 : obj.GetHashCode()); }
    }

    public static int HashValue<T>(this int hash, T value)
        where T : struct
    {
        unchecked { return hash * 23 + value.GetHashCode(); }
    }
}

Usage:
public class MyType<T>
{
    public string Name { get; set; }

    public string Description { get; set; }

    public int Value { get; set; }

    public IEnumerable<T> Children { get; set; }

    public override int GetHashCode()
    {
        return Hash.Base
            .HashObject(this.Name)
            .HashObject(this.Description)
            .HashValue(this.Value)
            .HashObject(this.Children);
    }
}

The compiler will ensure HashValue is not called with a class due to the generic type constraint. But there is no compiler support for HashObject since adding a generic argument also adds a boxing operation.

A: This is a static helper class that implements Josh Bloch's implementation; and provides explicit overloads to "prevent" boxing, and also to implement the hash specifically for the long primitives.
You can pass a string comparison that matches your equals implementation.
Because the Hash output is always an int, you can just chain Hash calls.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Sc.Util.System
{
    /// <summary>
    /// Static methods that allow easy implementation of hashCode. Example usage:
    /// <code>
    /// public override int GetHashCode()
    ///     => HashCodeHelper.Seed
    ///         .Hash(primitiveField)
    ///         .Hsh(objectField)
    ///         .Hash(iEnumerableField);
    /// </code>
    /// </summary>
    public static class HashCodeHelper
    {
        /// <summary>
        /// An initial value for a hashCode, to which is added contributions from fields.
        /// Using a non-zero value decreases collisions of hashCode values.
        /// </summary>
        public const int Seed = 23;

        private const int oddPrimeNumber = 37;

        /// <summary>
        /// Rotates the seed against a prime number.
        /// </summary>
        /// <param name="aSeed">The hash's first term.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static int rotateFirstTerm(int aSeed)
        {
            unchecked {
                return HashCodeHelper.oddPrimeNumber * aSeed;
            }
        }

        /// <summary>
        /// Contributes a boolean to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aBoolean">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, bool aBoolean)
        {
            unchecked {
                return HashCodeHelper.rotateFirstTerm(aSeed)
                        + (aBoolean
                                ? 1
                                : 0);
            }
        }

        /// <summary>
        /// Contributes a char to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aChar">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, char aChar)
        {
            unchecked {
                return HashCodeHelper.rotateFirstTerm(aSeed)
                        + aChar;
            }
        }

        /// <summary>
        /// Contributes an int to the developing HashCode seed.
        /// Note that byte and short are handled by this method, through implicit conversion.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aInt">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, int aInt)
        {
            unchecked {
                return HashCodeHelper.rotateFirstTerm(aSeed)
                        + aInt;
            }
        }

        /// <summary>
        /// Contributes a long to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aLong">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, long aLong)
        {
            unchecked {
                return HashCodeHelper.rotateFirstTerm(aSeed)
                        + (int)(aLong ^ (aLong >> 32));
            }
        }

        /// <summary>
        /// Contributes a float to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aFloat">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, float aFloat)
        {
            unchecked {
                return HashCodeHelper.rotateFirstTerm(aSeed)
                        + Convert.ToInt32(aFloat);
            }
        }

        /// <summary>
        /// Contributes a double to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aDouble">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, double aDouble)
            => aSeed.Hash(Convert.ToInt64(aDouble));

        /// <summary>
        /// Contributes a string to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aString">The value to contribute.</param>
        /// <param name="stringComparison">Optional comparison that creates the hash.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(
                this int aSeed,
                string aString,
                StringComparison stringComparison = StringComparison.Ordinal)
        {
            if (aString == null)
                return aSeed.Hash(0);
            switch (stringComparison) {
                case StringComparison.CurrentCulture :
                    return StringComparer.CurrentCulture.GetHashCode(aString);
                case StringComparison.CurrentCultureIgnoreCase :
                    return StringComparer.CurrentCultureIgnoreCase.GetHashCode(aString);
                case StringComparison.InvariantCulture :
                    return StringComparer.InvariantCulture.GetHashCode(aString);
                case StringComparison.InvariantCultureIgnoreCase :
                    return StringComparer.InvariantCultureIgnoreCase.GetHashCode(aString);
                case StringComparison.OrdinalIgnoreCase :
                    return StringComparer.OrdinalIgnoreCase.GetHashCode(aString);
                default :
                    return StringComparer.Ordinal.GetHashCode(aString);
            }
        }

        /// <summary>
        /// Contributes a possibly-null array to the developing HashCode seed.
        /// Each element may be a primitive, a reference, or a possibly-null array.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aArray">CAN be null.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, IEnumerable aArray)
        {
            if (aArray == null)
                return aSeed.Hash(0);
            int countPlusOne = 1; // So it differs from null
            foreach (object item in aArray) {
                ++countPlusOne;
                if (item is IEnumerable arrayItem) {
                    if (!object.ReferenceEquals(aArray, arrayItem))
                        aSeed = aSeed.Hash(arrayItem); // recursive call!
                } else
                    aSeed = aSeed.Hash(item);
            }
            return aSeed.Hash(countPlusOne);
        }

        /// <summary>
        /// Contributes a possibly-null array to the developing HashCode seed.
        /// You must provide the hash function for each element.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aArray">CAN be null.</param>
        /// <param name="hashElement">Required: yields the hash for each element
        /// in <paramref name="aArray"/>.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash<T>(this int aSeed, IEnumerable<T> aArray, Func<T, int> hashElement)
        {
            if (aArray == null)
                return aSeed.Hash(0);
            int countPlusOne = 1; // So it differs from null
            foreach (T item in aArray) {
                ++countPlusOne;
                aSeed = aSeed.Hash(hashElement(item));
            }
            return aSeed.Hash(countPlusOne);
        }

        /// <summary>
        /// Contributes a possibly-null object to the developing HashCode seed.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="aObject">CAN be null.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int Hash(this int aSeed, object aObject)
        {
            switch (aObject) {
                case null :
                    return aSeed.Hash(0);
                case bool b :
                    return aSeed.Hash(b);
                case char c :
                    return aSeed.Hash(c);
                case int i :
                    return aSeed.Hash(i);
                case long l :
                    return aSeed.Hash(l);
                case float f :
                    return aSeed.Hash(f);
                case double d :
                    return aSeed.Hash(d);
                case string s :
                    return aSeed.Hash(s);
                case IEnumerable iEnumerable :
                    return aSeed.Hash(iEnumerable);
            }
            return aSeed.Hash(aObject.GetHashCode());
        }

        /// <summary>
        /// This utility method uses reflection to iterate all specified properties that are readable
        /// on the given object, excluding any property names given in the params arguments, and
        /// generates a hashcode.
        /// </summary>
        /// <param name="aSeed">The developing hash code, or the seed: if you have no seed, use
        /// the <see cref="Seed"/>.</param>
        /// <param name="aObject">CAN be null.</param>
        /// <param name="propertySelector"><see cref="BindingFlags"/> to select the properties to hash.</param>
        /// <param name="ignorePropertyNames">Optional.</param>
        /// <returns>A hash from the properties contributed to <c>aSeed</c>.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int HashAllProperties(
                this int aSeed,
                object aObject,
                BindingFlags propertySelector
                        = BindingFlags.Instance
                        | BindingFlags.Public
                        | BindingFlags.GetProperty,
                params string[] ignorePropertyNames)
        {
            if (aObject == null)
                return aSeed.Hash(0);
            if ((ignorePropertyNames != null)
                    && (ignorePropertyNames.Length != 0)) {
                foreach (PropertyInfo propertyInfo in aObject.GetType()
                        .GetProperties(propertySelector)) {
                    if (!propertyInfo.CanRead
                            || (Array.IndexOf(ignorePropertyNames, propertyInfo.Name) >= 0))
                        continue;
                    aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));
                }
            } else {
                foreach (PropertyInfo propertyInfo in aObject.GetType()
                        .GetProperties(propertySelector)) {
                    if (propertyInfo.CanRead)
                        aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));
                }
            }
            return aSeed;
        }

        /// <summary>
        /// NOTICE: this method is provided to contribute a <see cref="KeyValuePair{TKey,TValue}"/> to
        /// the developing HashCode seed; by hashing the key and the value independently. HOWEVER,
        /// this method has a different name since it will not be automatically invoked by
        /// <see cref="Hash(int,object)"/>, <see cref="Hash(int,IEnumerable)"/>,
        /// or <see cref="HashAllProperties"/> --- you MUST NOT mix this method with those unless
        /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise
        /// the generated hash code will not be consistent. This method itself ALSO will not invoke
        /// this method on the Key or Value here if that itself is a KeyValuePair.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="keyValuePair">The value to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int HashKeyAndValue<TKey, TValue>(this int aSeed, KeyValuePair<TKey, TValue> keyValuePair)
            => aSeed.Hash(keyValuePair.Key)
                    .Hash(keyValuePair.Value);

        /// <summary>
        /// NOTICE: this method is provided to contribute a collection of <see cref="KeyValuePair{TKey,TValue}"/>
        /// to the developing HashCode seed; by hashing the key and the value independently. HOWEVER,
        /// this method has a different name since it will not be automatically invoked by
        /// <see cref="Hash(int,object)"/>, <see cref="Hash(int,IEnumerable)"/>,
        /// or <see cref="HashAllProperties"/> --- you MUST NOT mix this method with those unless
        /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise
        /// the generated hash code will not be consistent. This method itself ALSO will not invoke
        /// this method on a Key or Value here if that itself is a KeyValuePair or an Enumerable of
        /// KeyValuePair.
        /// </summary>
        /// <param name="aSeed">The developing HashCode value or seed.</param>
        /// <param name="keyValuePairs">The values to contribute.</param>
        /// <returns>The new hash code.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int HashKeysAndValues<TKey, TValue>(
                this int aSeed,
                IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
        {
            if (keyValuePairs == null)
                return aSeed.Hash(null);
            foreach (KeyValuePair<TKey, TValue> keyValuePair in keyValuePairs) {
                aSeed = aSeed.HashKeyAndValue(keyValuePair);
            }
            return aSeed;
        }
    }
}

A: I ran into an issue with floats and decimals using the implementation selected as the answer above.
This test fails (floats; hash is the same even though I switched 2 values to be negative):
        var obj1 = new { A = 100m, B = 100m, C = 100m, D = 100m};
        var obj2 = new { A = 100m, B = 100m, C = -100m, D = -100m};
        var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);
        var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);
        Assert.IsFalse(hash1 == hash2, string.Format("Hashcode values should be different   hash1:{0}  hash2:{1}",hash1,hash2));

But this test passes (with ints):
        var obj1 = new { A = 100m, B = 100m, C = 100, D = 100};
        var obj2 = new { A = 100m, B = 100m, C = -100, D = -100};
        var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);
        var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);
        Assert.IsFalse(hash1 == hash2, string.Format("Hashcode values should be different   hash1:{0}  hash2:{1}",hash1,hash2));

I changed my implementation to not use GetHashCode for the primitive types and it seems to work better
    private static int InternalComputeHash(params object[] obj)
    {
        unchecked
        {
            var result = (int)SEED_VALUE_PRIME;
            for (uint i = 0; i < obj.Length; i++)
            {
                var currval = result;
                var nextval = DetermineNextValue(obj[i]);
                result = (result * MULTIPLIER_VALUE_PRIME) + nextval;

            }
            return result;
        }
    }

    private static int DetermineNextValue(object value)
    {
        unchecked
        {

                int hashCode;
                if (value is short
                    || value is int
                    || value is byte
                    || value is sbyte
                    || value is uint
                    || value is ushort
                    || value is ulong
                    || value is long
                    || value is float
                    || value is double
                    || value is decimal)
                {
                    return Convert.ToInt32(value);
                }
                else
                {
                    return value != null ? value.GetHashCode() : 0;
                }
        }
    }

A: In case you want to polyfill HashCode from netstandard2.1
public static class HashCode
{
    public static int Combine(params object[] instances)
    {
        int hash = 17;

        foreach (var i in instances)
        {
            hash = unchecked((hash * 31) + (i?.GetHashCode() ?? 0));
        }

        return hash;
    }
}

Note: If used with struct, it will allocate memory due to boxing

A: Can try to adopt approach from C++ Boost libraries. Something like this:
class HashUtil
{
  public static int HashCombine(int seed, int other)
  {
    unchecked
    {
      return other + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
  }
}

and then:
class MyClass
{
  private string _field1;
  private int _field2;
  private AnotherClass _field3;
  private YetAnotherClass _field4;

  public override int GetHashCode()
  {
    int result = HashUtil.HashCombine(_field1.GetHashCode(), _field2);
    result = HashUtil.HashCombine(result, _field3.GetHashCode());
    return HashUtil.HashCombine(result, _field4.GetHashCode());
  }
}

A: I want to add my newest findings to this thread I came back to so often.
My current visual studio / project setup provides the functionallity to automatically refactors tuples to structs. This will generate a GetHashCode function like so:
        public override int GetHashCode()
        {
            int hashCode = -2088324004;
            hashCode = hashCode * -1521134295 + AuftragGesperrt.GetHashCode();
            hashCode = hashCode * -1521134295 + Auftrag_gesperrt_von.GetHashCode();
            hashCode = hashCode * -1521134295 + Auftrag_gesperrt_am.GetHashCode();
            return hashCode;
        }

EDIT: to clarify AuftragGesperrt, Auftrag_gesperrt_von and Auftrag_gesperrt_am are properties. If the microsoft devs use this function its probably not too bad of a solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Download and write image data in Julia I'm using the get function in the Julia Requests package (https://github.com/loladiro/Requests.jl) to download files. Some of the files are PNG images, and when I write the data in the returned object to a file:
x = get("url here")
outfile = open("file.png", "w")
write(outfile, x.data)
close(outfile)

...it does write the data to the file, but when I try to open it as an image, I get a file corruption warning.
It seems like get isn't downloading the file as binary, because when I download the file using the R function download.file() and the mode="wb" (write-binary) argument, I get different data in the file, and it opens successfully as an image.
Anyone have a good idea for how to download the PNG data correctly, or binary data in general?

A: The Requests package exhibits strange behaviour for me, where getting the same URL multiple times results in different data lengths, usually much shorter than the file. Anyhow, the HTTPClient package seems to work for me:
using HTTPClient
png = get("http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png")
outfile = open("file.png", "w")
write(outfile, png.body.data)
close(outfile)

(Julia also has the convenience function download(url, filename) for this special case.)

A: You can do this with download and the HTTP.jl package, the pwd() is there to download the file to your local directory
using HTTP
HTTP.download("https://www.someURL.JPG",pwd())


text:
Q: How to get columns in UITableView
Possible Duplicate:
How to display multiple columns in a UITableView?

I have an UITableView with 30 rows. I would like each row to have a date, a title and a name.
Right now it's like this:
Oct 29 name title

But the names and titles change so I have something like that :
Oct 29 name title
Oct 30 biggername biggertitle
Oct 30 xx title

I would like to make 3 equals columns like this:
Oct 29 | name | title
Oct 31 | b... | bi...
Oct 30 | xx   | title

How can I do that in my UITableView?

A: Best and easy way to get this thing use UITableViewCustomCell.
See this link - Custom tableView Cell
In cell XIB take 3 UILabel for each row then use them as your columns.
If this is not suitable for you just search Custom TableView cell on google :)

A: The best way I have managed to accomplish this was with a custom UITableViewCell that had a label for each column.  This way you can specify the width of the "columns" as the width of each label, then set their text in your cellForRowAtIndexPath

A: For UITableViewCell you can do this task by making 3 UILabel of same width and then add all of these UILabel in cell
[cell addSubview:yourLabel];

And if you want to add this separate image between then just make a UIImageView and then add this UIImageView as subView of cell.
[cell addSubview:yourImage];


text:
Q: Segmentation fault in CLI when inserting `text` greater than 7000 bytes I'm using the following to run a direct insert query in a Magento Shell script.
Mage::getSingleton('core/resource')->getConnection('core_read')->query($q)

One of the string values goes into a text column, and when this string exceeds about 7000 bytes, PHP crashes and a Segmentation fault (core dumped) error occurs.
The 7000 bytes figure is an approximate string size as I was truncating the string in blocks to see at what size an error occurs.
Does anyone have a clue why this happens and how to fix it? The text column accepts much more than 7000 bytes and when I run $q in MySQLyog, it inserts just fine.
The string in question is something like... (array of image URLs imploded with a ,)
http://www.mysite.com/media/catalog/product/cache/0/small_image/135x/images/catalog/product/placeholder/small_image.jpg,http://www.mysite.com/media/catalog/product/cache/0/small_image/135x/images/catalog/product/placeholder/small_image.jpg,http://www.mysite.com/media/catalog/product/cache/0/small_image/135x/images/catalog/product/placeholder/small_image.jpg,http://www.mysite.com/media/catalog/product/cache/0/small_image/135x/images/catalog/product/placeholder/small_image.jpg,... (just repeated ~40 times)

And each of these image URL are obtained via (pesudo code)
foreach list of products {
    $product= Mage::getModel('catalog/product')->load($id);
    $myImgUrl[] = (string)Mage::helper('catalog/image')->init($product, 'small_image')->resize(135);
}

EDIT:
I'd like to add that segmentation fault error occurs whether that particular query is run on the x-th iteration or 1st iteration of the foreach loop.
I also see that at the end of my shell script, memory_get_usage() is over 670 MB.. I see the usage go up at every iteration starting from about 16MB before the first iteration. I am using the same variables, which are used to write to the DB, at every loop.
Update:
I managed to avoid this problem something like below instead of ...->load($id). Fooman provided some insight into this problem in his answer in this thread [Link];
Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('my_atts')
    ->addAttributeToFilter('entity_id', $id)
    ->getFirstItem();
I understand. Your gist was very helpful. Although it's something I've done before, I didn't realize the memory impact. I replaced all of the ...->load() with your recommendation, ...->getCollection() and everything is well. Memory usage is constant around 16MB and noticeably faster.

A: As suggested by the below SO thread you may have run out of memory if you are (as I suspect) running this from the CLI.
To increase your PHP CLI memory_limit to the minimum recommended 256MB, you must first locate the correct INI file loaded for the CLI. To do so:
$ php -i | grep "Loaded Configuration"

Which will return something akin to:
Loaded Configuration File => /usr/local/etc/php/5.4/php.ini

Then you will edit the php.ini file at that location and increase memory_limit to a minimum 256MB.
After you save and close you can check that it's been updated with:
$ php -i | grep memory_limit

In all luck it should return:
memory_limit => 256M => 256M

Parting thoughts:
This isn't necessarily Magento's (or even PHP's) fault. Magento handles "direct" inserts of many many hundreds of kilobytes larger than your script. I suspect there are other factors at play, like how you're deriving the URLs in the first place. If you're doing Mage::getModel('catalog/product')->load() in a loop, for instance.
In short, you may have created some memory leaks, instantiated objects unnecessarily, loaded massive objects or collections from the db unnecessarily, and coded your way into this position.
Best of luck.

Sources:
https://stackoverflow.com/questions/12191996/php-in-commandline-segmentation-fault-core-dumped-debug-while-running-phpi
https://stackoverflow.com/questions/15714909/php-what-does-segmentation-fault-core-dumped-error-means


text:
Q: using ionicons 5 in vue.js I want to use ionicons 5 in my vue.js project.
<ion-icon name="heart"></ion-icon>

If I use:
<script type="module" src="https://unpkg.com/ionicons@5.0.0/dist/ionicons/ionicons.esm.js"></script>

every thing works fine but I want to use it just like any other npm package and bundle it with my other modules using webpack.
What should I do?
What is the correct way of using ionicons 5 in a vue.js project (without using script tag & linking to cdn)
font awesome provides an official vue.js component:
https://fontawesome.com/how-to-use/on-the-web/using-with/vuejs


text:
Q: How to change previous date log file permision to read only in Log4Net? I am using Log4Net in my window application, Now i want to change the permission of my all previous date logs to read only automatically and only current date log file will remain same or not changed. How can i do this using Log4Net or is it possible in any other plugin like Elmah ?

A: This is not possible out of the box. You can invest to extend the file appender you are using to make the file ReadOnly when it is rolled. You can see the find the log4net source code here. Look for the appenders and then extend/ or copy that appender in you project. Make the changes and then use your own appender in the configuration.


text:
Q: How was Dumbledore able to give the snitch to Harry in his will? If the golden snitch was the school's property, not that of Dumbledore, then how come he mentions the snitch in his will to Harry?

A: Snitches remember who touched them. The Ministry had a clue that something might happen if Harry touches that particular snitch so even if it was school property, Scrimegour willingly gave it to Harry in the hope that it will reveal something that Dumbledore meant to show only to Harry. And once Harry had the snitch, it would be weird to take it back.
In 7th chapter of 7th book:

"I don't think there's anything hidden in the icing," said Scrimgeour,
  "but a Snitch would be a very good hiding place for a small
  object. You know why, I'm sure?"
  Harry shrugged. Hermione, however, answered: Harry thought
  that answering questions correctly was such a deeply ingrained habit
  she could not suppress the urge.
  "Because Snitches have flesh memories," she said.
  "What?" said Harry and Ron together; both considered Hermione's
  Quidditch knowledge negligible.
  "Correct," said Scrimgeour. "A Snitch is not touched by bare skin
  before it is released, not even by the maker, who wears gloves. It
  carries an enchantment by which it can identify the first human to
  lay hands upon it, in case of a disputed capture. This Snitch" — he
  held up the tiny golden ball — "will remember your touch, Potter.
  It occurs to me that Dumbledore, who had prodigious magical skill,
  whatever his other faults, might have enchanted this Snitch so that
  it will open only for you."

A: Used snitches seem to be given away by the school as prizes to the seeker who caught it. We see Harry with a Snitch (admittedly described as "stolen") in the common room after the game and is letting a cat play with it. Clearly it's not a high-value item after its 'flesh memory' has been activated or he'd be much more wary about letting people see him with it.

The Snitch he had caught earlier was now zooming around and
around the common room; people were watching its progress as though
hypnotized and Crookshanks was leaping from chair to chair, trying to
catch it.
Harry Potter and the Order of the Phoenix

As Headmaster of Hogwarts, it's presumably within Dumbledore's gift to give himself something that would otherwise be considered junk.

A: The answer probably is concerned with 'how can Dumbledore give the snitch' in his will as he obviously has 'given' it.
Recall how he also tried to give Harry the sword but this was blocked by the Ministry (mainly because they didn't know where the sword was).
However, with a snitch, it may well have been allowed but the Ministry could also have blocked it - why didn't they ?
Everyone knows that snitches have 'flesh memory' and a snitch in and of itself is pretty useless outside of a Quidditch match. The Ministry were therefore asking why did Dumbledore bequeath a snitch and they came to the conclusion that there was more to it than meets the eye. Could it be a message from Dumbledore to Harry or could it conceal something useful. Remember Dumbledore didn't let the Ministry in on his plans which left them somewhat 'put out'.
So, I suspect that the Ministry let it pass so, when the snitch was given over to Harry (by the Minister of Magic himself), something of Dumbledore's plans would be revealed to them via flesh memory.
As we know this never happened (due to how Harry caught the first snitch and 'opens at the close') and the Ministers reaction of disappointment when nothing happens speaks volumes...


text:
Q: Not able to enter decimal value in Ionic 2 RC.1 number field I am using Ionic 2 RC.1. I want to have a field which accept dollar amount in it up to 2 decimal places.
      <ion-item>
        <ion-label floating>Dollar AMount <label class="mandatory-indicator">*</label></ion-label>
        <ion-input type="number" [formControl]="empForm.controls['wsAmtEarned']"  maxlength="30" size="30" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"></ion-input>
      </ion-item>

Whenever I enter decimal value (say 5.3) in it, it starts giving me error that the Nearest possible values are 5 and 6. How cal I modify it to satisfy my requirements.

A: Right now, Ionic 2 seems to support only the following input types, which correspond to HTML5 input types:

The HTML input type (text, password, email, number, search, tel, or
  url)

The Number input type in HTML5 defaults to an integer. Actually, a numeric with a default step of 1. So, you could try to set the step attribute on the input (to step="0.1") and see if this is propagated to Ionic.
Otherwise, change the type to text and allow your pattern validator to take over.


text:
Q: OpenGL ES3: no matching overloaded function found for packUnorm2x16 I am trying to pack 2 float values into 1 uint value using packUnorm2x16 method of OpenGL ES3 GLSL. But the compilation of the shader fails with 'packUnorm2x16': no matching overloaded function found error.
This is my fragment shader:
varying highp vec2 vDisplacement;

void main() {
  gl_FragColor = vec4(packUnorm2x16(vDisplacement), vec3(0.0));
}

I am trying to render a result to a GL_R32UI texture.

A: packUnorm2x16 is supported since OpenGL ES 3.0. You've to add the version qualifier #version 300 es to the first lien of the fragment shader:
#version 300 es

varying highp vec2 vDisplacement;

void main() {
    gl_FragColor = vec4(packUnorm2x16(vDisplacement), vec3(0.0));
}


text:
Q: Visualize motion/gesture from acceleration data I have implemented a gesture detection algorithm where a user can define his own gestures. The gestures are defined by acceleration values send from an accelerometer.
Now my question is: Is it possible to visualize the performed gesture, so that the user can identify what gesture he performed?
My first idea and try was just to use Verlet Velocity Integration (as describec here: http://lolengine.net/blog/2011/12/14/understanding-motion-in-games) to calculate the corresponding positions and use those to form a line strip in OpenGL. The rendering works, but the result is not at all what the performed gesture looked like.
This is my code:
    float deltaTime = 0.01;
    PosData null;
    null.x = 0.0f;
    null.y = 0.0f;
    null.z = 0.0f;
    this->vertices.push_back(null);
    float velX = 0.0f;
    float velY = 0.0f;
    float velZ = 0.0f;

    for (int i = 0; i < accData.size(); i++) {
        float oldVelX = velX;
        float oldVelY = velY;
        float oldVelZ = velZ;
        velX = velX + accData[i].x * deltaTime;
        velY = velY + accData[i].y * deltaTime;
        velZ = velZ + accData[i].z * deltaTime;
        PosData newPos;
        newPos.x = vertices[i].x + (oldVelX + velX) * 0.5 * deltaTime;
        newPos.y = vertices[i].y + (oldVelY + velY) * 0.5 * deltaTime;
        newPos.z = vertices[i].z + (oldVelZ + velZ) * 0.5 * deltaTime;
        this->vertices.push_back(newPos);
    }

I am using a deltaTime of 0.01 because my accelerometer sends the acceleration data every 10 milliseconds.
Now i am wondering: Is there something wrong with my calculation? Could it even work this way? Is there a library which can do this? Any other suggestions?

A: as the theoretical physics and monte-carlo-simulation man, I've thought about the discrepancies you've observed. You wrote that the "real" gesture curve (3D) didn't resemble at all the calculatet curve. You might want to consider several aspects of the problem at hand. First, what do we know about the "real" gesture curve in space. We certainly do have "some" curve in mind, but that needn't look much like the "real" curve performed by one's hand. Second, what do we know about the quality of the accelerometer, about its accuracy, about its latency or other intricacies? Third point, what do we know about the "measured" acceleration data, do they fit "some" nice and smooth curve when drawn in x-y-plot shape? If that curve isn't really very smooth-looking, then one needs assumptions about the acceleration data to perform a linear, or better, a spline-fit. Afterwards you can integrate simply by analytical formulae. -- You might think in terms of signing electronically when the UPS parcel service asks you to, what does your signature look like on that pad? This is what probably happens with your acceleration system, without some "intelligent" curvature-smoothing algorithm. Hope my comment could be helpful in one way or another ... Regards, M.


text:
Q: Changing "Region format" in Windows programatically (C#) In Windows you have this window where you can set which format you want on your date and time (and currencies if you click "Additional Settings").
How do you change this programatically?
I have already found links telling me to set it using the CultureInfo classes. This is not a good solution as this will only set it for one application, not the entire system.
I've found promising links pointing to HKCurrentUser\ControlPanel\Internaltional where I can see many of these settings, but from what I've read, changing settings in the registry requires a reboot of the computer. Setting the values directly in the window screenshot below does not require a reboot.
When I do an actual update in the window screenshot below I can see that most of the values in the registry changes. If I am to do that programatically it seems a bit overkill to need to change all of them when I just select one item from the combobox.
Surely there's a better way, i.e. Windows API Calls (which also lets me handle the "Additional Settings")?

A: In powershell 3, was introduced Get-Culture and Set-Culture cmdlets. I am sure, it work from Win 8, I am not sure about Win 7 and Vista.
In powershell you can change user regional settings like this:
$culture = Get-Culture
$culture.DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
$culture.DateTimeFormat.LongDatePattern = 'dddd, d MMMM, yyyy'
$culture.DateTimeFormat.ShortTimePattern = 'h:mm tt'
$culture.DateTimeFormat.LongTimePattern = 'h:mm:ss tt'
$culture.NumberFormat.CurrencyDecimalSeparator = ":"
Set-Culture $culture

You can find other options by executing $culture | get-member ,
 $culture.DateTimeFormat | Get-Member,
 $culture.NumberFormat | Get-Member
You can very easy host powershell script in your c# application. https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx


text:
Q: tick(grid) is overwriting with Y Axis in D3.js I have created Js fiddle here Please look
Required like below X and Y  axis with black and grids are lighter

But getting below

Create YAxis scale and create ticks
I set tickSizeInner(margin-width+100)  but its not work
    var yScaleTest = d3.scaleLinear()
  .domain([
    d3.min(this.materialGraphDataSource[0].materials, function (d) {
      return d3.min(d.materialStocks, function (d) {
        return d.item2;
      })
    }),
    d3.max(this.materialGraphDataSource[0].materials, function (d) {
      return d3.max(d.materialStocks, function (d) {
        return d.item2;
      })
    })])
  .range([height - margin, 0])
  .nice();

   /* Add Axis into SVG */
var xAxis = d3.axisBottom(xScaleTest)
  .ticks(d3.timeMonth.every(1))
  .tickSizeOuter(0)
  .tickSizeInner(-height + margin)
  .tickFormat(d3.timeFormat("%b -%Y"));

var yAxis = d3.axisLeft(yScaleTest)
 .ticks(14)
  .tickSizeOuter(0)
  .tickSizeInner(margin-width+200)

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .call(g => g.selectAll(".tick line")
      .attr("class", "axis_bar")
      .attr("stroke", "#E8E8E8"))

A: Select the first tick line, the one at the bottom, and remove it. JSFiddle
  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .call(g => g.select('.tick:first-of-type line').remove())
    .call(g => g.selectAll(".tick line")
      .attr("class", "axis_bar")
      .attr("stroke", "#E8E8E8"))


text:
Q: Does simple past always indicate an event that happened at a 'specific time' in the past? From what I understand, the verb tense 'simple past' is used for an event that happened at a specific time in the past.
The sentence 'Sam played tennis yesterday.' is simple past because it happened at a specific time in the past (yesterday).
However, if I change the sentence to:

'Sam played tennis.'

What will be the verb tense in this case? This event did not happen at a specific time in the past. Will it still be simple past or will it be something else?
Also if I change the sentence even more to:

'Sam used to play tennis.'

What will be the verb tense now? It feels like simple past to me, but is it?

A: The first two statements are equivalent:

Sam played tennis yesterday.
  Sam played tennis.

Simple past is used to show that the subject has completed an action. A specific time frame for the event is intended when using simple past tense. However, the speaker can choose to include or omit the actual time of the event.
The next statement is:

Sam used to play tennis.

'Used to' is an imperfect form of verb that combines the past tense and the present tense. It is used to imply a habitual action: one that has repeatedly occurred in the past. In the above statement, 'used to' means that Sam had a habit of playing tennis at some point in the past. Sam does not have this habit anymore.
You can find more information about 'Used to' on this Wikipedia page. A tutorial on this usage can be found here.


text:
Q: RDP Session Credentials Validation I need a solution for setting username & password validation for my RDP Client application.
The goal is to close the connection if the credentials (username or password) are incorrect.
How can I programmatically validate the session when one of the credentials is incorrect?
try
{
   rdp.Server = txtServer.Text;
   rdp.UserName = txtUserName.Text;

   IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
   secured.ClearTextPassword = txtPassword.Text;

   rdp.OnLoginComplete += RdpOnOnLoginComplete;
   rdp.OnLogonError += rdp_OnLogonError;
   rdp.Connect();
}

catch (Exception Ex)
{
      MessageBox.Show("Error Connecting", "Error connecting to remote desktop " + txtServer.Text + " Error:  " + Ex.Message,MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Events
void rdp_OnLogonError(object sender, AxMSTSCLib.IMsTscAxEvents_OnLogonErrorEvent e)
    {
       throw new NotImplementedException();
    }

private void RdpOnOnLoginComplete(object sender, EventArgs eventArgs)
    {
       throw new NotImplementedException();
    }

A: Importantly though, it seems that when using either the old TSAC control or the new RDPC control to connect to Server 2008 R2 (including Windows Home Server 2011) the control does not provide any "failed logon" feedback. I assume this was a security measure meant to help prevent hacking and cracking using these controls.
Unlike the stand-alone RDP Client utility program, a failed logon results in the connection being retained leaving the user looking at the remote system's logon desktop. This allows the user to manually logon on there but prevents a program from getting feedback on the logon failure and trying another user/password.
So... if your servers are all earlier than Server 2008 R2 you might still use one or the other of these controls to attempt an RDP connection and attempt a logon, reporting failure on bad credentials.


text:
Q: Why did the Lizard formula work better for Komodo? In Avengers: The Initiative, Komodo's abilities stem from using Dr Curt Connor's lizard formula.

In addition to regrowing her legs, she is shown to have more control over the change process than Connor's and does not suffer from the same personality issues as The Lizard.
Has a reason been given for this?

A: Komodo's origin is covered in more detail in Avengers: The Initiative Special - "The Real Thing".
Essentially, instead of it being a straight theft she had worked with Connors for some time before to perfect the formula for her DNA.

A: Although no official reason has been given for this, it should be noted that this is not the first instance of something like this happening. When Cindy Moon became Silk after being bitten by the radioactive spider that turned Peter Parker into Spider-Man, she produced a natural web-shooting ability which Peter did not. Similarly, when Jennifer Walters was given a blood transfusion from Bruce Banner, she became She-Hulk, although much more in control; she retained her intelligence and could switch back and forth when desired, although she mostly chose to keep her Hulk form. This is in contrast to Bruce Banner's Hulk in the sense that when Bruce becomes angry, frustrated or hurt, he 'Hulks out' and goes on a rampage.

A: in No Turning Back, Slott's Amazing Spider-Man story he pretty much states that The Lizard persona is all Curt Connors Anger and bitterness of his injury and lot in life made form so Komodo who is of a somewhat healthier mindset is pretty much one mind in both forms


text:
Q: .net WP8.1/Win10 UWP: Namespace for MapControl not found in Visual Studio Designer Edit: the described issue below occurs also in a Win 10 UWP application (VS2015, Win10) when using the MapControl.
I have a weird problem using the MapControl in a Windows Phone 8.1 (universal app) application. After adding the control to a page, Visual Studio says The name "MapControl" does not exist in the namespace "using:Windows.UI.Xaml.Controls.Maps". Building the app works, I can deploy it to the phone and the map is shown and everything is fine - but I cannot use the Designer for this page any longer since it claims that error.
The problem occured in a bigger project originally started in VS2013 (update 4) on Windows 8.1. My first thought was that my VS-installation was kind of broken. But also after a clean new installation of Windows 10 (10240) and VS2015 RTM the problem occured. My steps to reproduce are quite simple:

*

*Create a new project from template "Blank App (Universal Windows 8.1)"

*Open the MainPage.xaml of the WindowsPhone subproject

*Double click the MapControl in the toolbox

*Note that the MapControl is added to the Grid in xaml and it is shown in side-by-side design view. Everything seems to be ok.

*I can now add more controls to the page just by clicking the toolbox. I can modify the controls on the page with the mouse in the designer (e.g. rearrange them) and I can change their properties by the properties pane. Everything is still ok.

*But when I either close and reopen that page (or the whole project) in the designer or when I start to edit the xaml directly with the keyboard, the designer fails and claims the error described above.

What's the problem here? How can I make Visual Studio designer to work with pages with MapControls again? First I thought of a bug in VS2013 - but that simple to reproduce, not fixed in VS2015 and no information about it on the internet? What did I wrong?

A: There is a bug on Visual Studio Tools for Universal Windows Apps 1.0 causing this issue with the map, installing this update should fix the issue Update

Procedure to correctly use the map sdk
Windows 8.1

*

*Go to Tools-> extension and update -> install Bing Map SDK.

*Right click on the project->Add reference->Windows->Extensions->Bing maps

*Set configuration to x86 (Configuration Properties -> Configuration)

*Add the map reference to your page using xmlns:maps="using:Bing.Maps"

*Adding this line to your xaml <maps:Map />
and now you are good to go

Windows Phone and Windows 10 UAP

Add this reference in your xaml
xmlns:maps="using:Windows.UI.Xaml.Controls.Maps"

and then add this line to your xaml
<maps:MapControl />

A: Set configuration to x86 instead of "Any CPU". For prioritising fix upvote at https://connect.microsoft.com/VisualStudio/feedback/details/1659249/visual-studio-2015-rtm-uwp-the-name-mapcontrol-does-not-exist-in-the-namespace-using-windows-ui-xaml-controls-maps

A: Make the correct map library reference
xmlns:Maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"

Instead of
xmlns:Maps="using:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"


text:
Q: Pass row number as variable and reference other sheet I have a row of data on one sheet (Harvest targets) that I want to transpose to another sheet (Field worksheet) into an array.
On the second sheet (Field worksheet), I have a drop down list (A31) to choose the crop, and I have a cell next to it (I31) that outputs the row number the crop is on in the first sheet (Harvest targets). I am trying to use the following formula, but it's not working (I get an error):
=TRANSPOSE('Harvest targets'!(INDIRECT("X" & I31):INDIRECT("AU" & I31)))

Any ideas as to what I'm doing wrong? I'm trying to use INDIRECT to look up the correct row in the other sheet, which is set by I31, in a predetermined range of columns (X:AU).

A: INDIRECT is a little difficult to work with, especially in such constructions, as well as being volatile. INDEX is more appropriate here:
=TRANSPOSE(INDEX('Harvest targets'!X:X,I31):INDEX('Harvest targets'!AU:AU,I31))

Regards


text:
Q: how many reference count increase i now this is a silly question, but i still have some poor understanding about this case. It is about memory management and reference count, i have some doubt about how many reference count will increase if i use copy, alloc, and mutable copy. This is the code i have :
This is myController.h :
#import <UIKit/UIKit.h>

@interface myController : UIViewController {
NSMutableString *mutableStringCode;
}
@property (nonatomic, copy) NSMutableString *mutableStringCode;
@end

and this is myController.m
#import "myController.h"

@implementation myController

-(void)viewDidLoad{
    mutableStringCode = [[NSMutableStringCode alloc]init];
    [self refresh];

}

-(void)refresh{
    NSMutableString *myFileContents = [NSMutableString stringWithContentsOfFile:localPath encoding:NSUTF8StringEncoding error:&error];

    mutableStringCode = [myFileContents mutableCopy];

    //another code

    myFileContents = nil;
}

-(void)dealloc{
    [mutableStringCode release];

    [super dealloc];

}

@end

in this code, i have some doubts :
1. how many reference count increase in that mutableStringCode ?
2. is it a true way to set mutableStringCode property using copy not retain?
3. am i still have to alloc that mutableStringCode after i set it copy on property?
can some body describe it to me??
Thank you

A: *

*If you simply create an instance of the myController class, and then release it, everything will be fine. mutableStringCode will be created in viewDidLoad (if it will be called) and released in dealloc. It happens because alloc retains object.

*Every time you call refresh, these things happen:

*

*you create autoreleased mutable string myFileContents.

*you copy it to mutableStringCode, retaining it (copy retains object).

The main problem I see here is that during refresh you are not releasing already created mutableStringCode. So it stays retained in memory (it is usual memory leak).
You can try to catch these types of memory leaks with Analyse or with Instruments' Leaks tool.


text:
Q: Usage of pcl::CropHull Hello I am looking for a way to find out points/indices of point cloud which lie within a set of pre-defined polygon points/indices.
My Input would be either of the following.

*

*Set of indices of the cloud forming a 2D polygon. Eg : 21480, 4491, 20399, 19034, 21322, 5240, 5870, 21480

*Set of coordinates(x,y,z) which correspond to the above indices in the cloud.

enter image description here

A: May I politelly suggest you the documentation pcl::CropHull
In your case. the methods:
setHullCloud (PointCloudPtr points)
setCropOutside (bool crop_outside)
and then
filter (PointCloud &output)
should do the job.
If this did not answer your problem please be more specific to which problems you are exactly facing when using pcl::CropHull (with code if possible)


text:
Q: Keep getting Access to XMLHttpRequest at '(api url)' from origin '(localserver)' has been blocked by CORS policy I am working on my first API project and, also, I am new to this technology.
I have been successful in implementing "GET" method on Nasa's API https://api.nasa.gov/planetary/apod and also on dog API https://dog.ceo/api/breeds/image/random on both local as well as remote server.
But when I try to "GET" in the API developed by a private institution it works fine in Postman but not on my local server.
It keeps showing Access to XMLHttpRequest at '(api url)' from origin '(localserver)' has been blocked by CORS policy. No 'Access-Control-Allow-Origin' header is present on the requested resource.
HTML Doc:
<!DOCTYPE html>
<html>
    <head>
        <title>API</title>
    </head>
    <body>
        <div>
            PRINT
        </div>
        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="./script.js"></script>
    </body>
</html>

AJAX Request:
$.ajax({
    url: "api",
    method: "GET",
    data: {
        "Key": "(myapikey)",
        "UserID": "userid",
        "Password": "pass",
        "AwbNo": "someNumber"
    },
    success: function(data){
        console.log(data);
    },
}).fail(function(){
    console.log("error in script");
});

I tried the solutions like including the allow-access-control-origin header but it still showed the same error. Please help.
Edit 1:
I added the the following two lines to my ajax code:
crossDomain: true,
dataType: 'jsonp'

and now it shows the following error:
Cross-Origin Read Blocking (CORB) blocked cross-origin response "(api request)" with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Edit 2:
Added in AJAX code:
header:{
        "Access-Control-Allow-Origin":"*"
    }

Still showing the same error

A: CORS mechanizm in a web browser won't let you get resources from your api unless api would send you response with header Access-Controll-Allow-Origin with value of your domain or with wildcard (*).
So you must to change api response to return you this header
Access-Controll-Allow-Origin=<protocol://your_domain:port> or if you don't have access to changing api you can write simple proxy (simple rest api) to redirect request from your browser to actual endpoint.