问:
Why doesn't my C# code produce the same output when using AES CBC 128bit encryption as this website: https://cryptii.com/pipes/aes-encryption
This is what I want to achieve using AES 128bit CBC encryption converted to hexadecimal: "30487A117196A34DE5ADCD679BA0FE71". I can achieve this when I use the website: https://cryptii.com/pipes/aes-encryption

I am however not able to achieve this using C#. Here is the code I am using:

```<code>public static void Main(string[] args)
    {
        var key = "123456789012345678901234567890af";
        var text = "raiden";
        var iv = "01C2191CFA1B33D47246E8C76EB3A824";

        var value = EncryptValues(key, iv, text);
        DecryptValues(key, iv, value);

        Console.ReadLine();
    }

    public static string EncryptValues(string keyText, string ivText, string plainText)
    {
        var key = ParseBytes(keyText);
        var text = Encoding.Default.GetBytes(plainText);
        var iv = ParseBytes(ivText);

        var raw = SimpleEncrypt(new RijndaelManaged(), CipherMode.CBC, key, iv, text);

        var hexadecimalCipher = BytesToHex(raw);
        Console.WriteLine(hexadecimalCipher);
        return hexadecimalCipher.Replace(" ", string.Empty);
    }

    public static void DecryptValues(string keyText, string ivText, string cipherText)
    {
        var key = ParseBytes(keyText);
        var text = ParseBytes(cipherText);
        //var expectedText = ParseBytes("30487A117196A34DE5ADCD679BA0FE71"); // <<<<< this is the expected value
        var iv = ParseBytes(ivText);

        var dec = SimpleDecrypt(new RijndaelManaged(), CipherMode.CBC, key, iv, text);
        Console.WriteLine(Encoding.UTF8.GetString(dec));
    }
    public static byte[] ParseBytes(string strToParse, bool removeSeparator = false, string separator = " ")
    {
        // Basic check
        if (string.IsNullOrEmpty(strToParse))
            throw new ArgumentNullException();

        // Check from separator
        if (removeSeparator)
            strToParse = strToParse.Replace(separator, string.Empty);

        // Parse
        var bytes = new List<byte>();
        var counter = 0;
        var characterArray = strToParse.ToCharArray();
        for (int i = 0; i < strToParse.Length / 2; i++)
        {
            string byteString = $"{characterArray[counter]}{characterArray[counter + 1]}";
            var byteToAdd = byte.Parse(byteString, NumberStyles.HexNumber);
            bytes.Add(byteToAdd);
            counter += 2;
        }

        return bytes.ToArray();
    }

    public static byte[] HexToBytes(string str, string separator = " ")
    {
        if (str == null)
        {
            throw new ArgumentNullException();
        }

        if (separator == null)
        {
            separator = string.Empty;
        }

        if (str == string.Empty)
        {
            return new byte[0];
        }

        int stride = 2 + separator.Length;

        if ((str.Length + separator.Length) % stride != 0)
        {
            throw new FormatException();
        }

        var bytes = new byte[(str.Length + separator.Length) / stride];

        for (int i = 0, j = 0; i < str.Length; i += stride)
        {
            bytes[j] = byte.Parse(str.Substring(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            j++;

            // There is no separator at the end!
            if (j != bytes.Length && separator != string.Empty)
            {
                if (string.CompareOrdinal(str, i + 2, separator, 0, separator.Length) != 0)
                {
                    throw new FormatException();
                }
            }
        }

        return bytes;
    }

    public static string BytesToHex(byte[] bytes, string separator = " ")
    {
        if (bytes == null)
        {
            throw new ArgumentNullException();
        }

        if (separator == null)
        {
            separator = string.Empty;
        }

        if (bytes.Length == 0)
        {
            return string.Empty;
        }

        var sb = new StringBuilder((bytes.Length * (2 + separator.Length)) - 1);

        for (int i = 0; i < bytes.Length; i++)
        {
            if (i != 0)
            {
                sb.Append(separator);
            }

            sb.Append(bytes[i].ToString("x2"));
        }

        return sb.ToString();
    }

    public static byte[] SimpleEncrypt(SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key, byte[] iv, byte[] bytes)
    {
        algorithm.Mode = cipherMode;
        algorithm.Padding = PaddingMode.Zeros;
        algorithm.Key = key;
        algorithm.IV = iv;

        using (var encryptor = algorithm.CreateEncryptor())
        {
            return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
        }
    }

    public static byte[] SimpleDecrypt(SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key, byte[] iv, byte[] bytes)
    {
        algorithm.Mode = cipherMode;
        algorithm.Padding = PaddingMode.Zeros;
        algorithm.Key = key;
        algorithm.IV = iv;

        using (var encryptor = algorithm.CreateDecryptor())
        {
            return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
        }
    }
</code>```

Why doesn't the outputted encrypted string in hexadecimal match: "30487A117196A34DE5ADCD679BA0FE71" - it is outputted as: "72aa9bf0ee7d8e3db7e8c763d21371b3".

The thing that's most strange here is that both the expected value: "30487A117196A34DE5ADCD679BA0FE71" and the C# generated value: "72aa9bf0ee7d8e3db7e8c763d21371b3" decrypt correctly when fed to the decryption method returning "raiden"..

Any help on this one is greatly appreciated!

答: I used PKCS7 padding for the encryption (was using Zeros)</p>

Body:
This is what I want to achieve using AES 128bit CBC encryption converted to hexadecimal: "30487A117196A34DE5ADCD679BA0FE71". I can achieve this when I use the website: https://cryptii.com/pipes/aes-encryption

I am however not able to achieve this using C#. Here is the code I am using:

public static void Main(string[] args)
    {
        var key = "123456789012345678901234567890af";
        var text = "raiden";
        var iv = "01C2191CFA1B33D47246E8C76EB3A824";

        var value = EncryptValues(key, iv, text);
        DecryptValues(key, iv, value);

        Console.ReadLine();
    }

    public static string EncryptValues(string keyText, string ivText, string plainText)
    {
        var key = ParseBytes(keyText);
        var text = Encoding.Default.GetBytes(plainText);
        var iv = ParseBytes(ivText);

        var raw = SimpleEncrypt(new RijndaelManaged(), CipherMode.CBC, key, iv, text);

        var hexadecimalCipher = BytesToHex(raw);
        Console.WriteLine(hexadecimalCipher);
        return hexadecimalCipher.Replace(" ", string.Empty);
    }

    public static void DecryptValues(string keyText, string ivText, string cipherText)
    {
        var key = ParseBytes(keyText);
        var text = ParseBytes(cipherText);
        //var expectedText = ParseBytes("30487A117196A34DE5ADCD679BA0FE71"); // <<<<< this is the expected value
        var iv = ParseBytes(ivText);

        var dec = SimpleDecrypt(new RijndaelManaged(), CipherMode.CBC, key, iv, text);
        Console.WriteLine(Encoding.UTF8.GetString(dec));
    }
    public static byte[] ParseBytes(string strToParse, bool removeSeparator = false, string separator = " ")
    {
        // Basic check
        if (string.IsNullOrEmpty(strToParse))
            throw new ArgumentNullException();

        // Check from separator
        if (removeSeparator)
            strToParse = strToParse.Replace(separator, string.Empty);

        // Parse
        var bytes = new List<byte>();
        var counter = 0;
        var characterArray = strToParse.ToCharArray();
        for (int i = 0; i < strToParse.Length / 2; i++)
        {
            string byteString = $"{characterArray[counter]}{characterArray[counter + 1]}";
            var byteToAdd = byte.Parse(byteString, NumberStyles.HexNumber);
            bytes.Add(byteToAdd);
            counter += 2;
        }

        return bytes.ToArray();
    }

    public static byte[] HexToBytes(string str, string separator = " ")
    {
        if (str == null)
        {
            throw new ArgumentNullException();
        }

        if (separator == null)
        {
            separator = string.Empty;
        }

        if (str == string.Empty)
        {
            return new byte[0];
        }

        int stride = 2 + separator.Length;

        if ((str.Length + separator.Length) % stride != 0)
        {
            throw new FormatException();
        }

        var bytes = new byte[(str.Length + separator.Length) / stride];

        for (int i = 0, j = 0; i < str.Length; i += stride)
        {
            bytes[j] = byte.Parse(str.Substring(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            j++;

            // There is no separator at the end!
            if (j != bytes.Length && separator != string.Empty)
            {
                if (string.CompareOrdinal(str, i + 2, separator, 0, separator.Length) != 0)
                {
                    throw new FormatException();
                }
            }
        }

        return bytes;
    }

    public static string BytesToHex(byte[] bytes, string separator = " ")
    {
        if (bytes == null)
        {
            throw new ArgumentNullException();
        }

        if (separator == null)
        {
            separator = string.Empty;
        }

        if (bytes.Length == 0)
        {
            return string.Empty;
        }

        var sb = new StringBuilder((bytes.Length * (2 + separator.Length)) - 1);

        for (int i = 0; i < bytes.Length; i++)
        {
            if (i != 0)
            {
                sb.Append(separator);
            }

            sb.Append(bytes[i].ToString("x2"));
        }

        return sb.ToString();
    }

    public static byte[] SimpleEncrypt(SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key, byte[] iv, byte[] bytes)
    {
        algorithm.Mode = cipherMode;
        algorithm.Padding = PaddingMode.Zeros;
        algorithm.Key = key;
        algorithm.IV = iv;

        using (var encryptor = algorithm.CreateEncryptor())
        {
            return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
        }
    }

    public static byte[] SimpleDecrypt(SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key, byte[] iv, byte[] bytes)
    {
        algorithm.Mode = cipherMode;
        algorithm.Padding = PaddingMode.Zeros;
        algorithm.Key = key;
        algorithm.IV = iv;

        using (var encryptor = algorithm.CreateDecryptor())
        {
            return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
        }
    }

Why doesn't the outputted encrypted string in hexadecimal match: "30487A117196A34DE5ADCD679BA0FE71" - it is outputted as: "72aa9bf0ee7d8e3db7e8c763d21371b3".

The thing that's most strange here is that both the expected value: "30487A117196A34DE5ADCD679BA0FE71" and the C# generated value: "72aa9bf0ee7d8e3db7e8c763d21371b3" decrypt correctly when fed to the decryption method returning "raiden"..

Any help on this one is greatly appreciated!


来源: stackexchange

问:
Marker Color based on String Value Plotly Python
Pretty simple question here, but I cannot seem to figure it out. I have a dataframe column with 3 possible values:

print(df['Site'])

0        ABC
1        EFG
2        ABC
3        ABC
4        HIJ
```

<p>When I plot, each site has the same color, but I would each marker to have a color to represent the site. I have tried to following 2 options with no luck:</p>

<pre class="lang-py prettyprint-override"><code>fig.add_trace(go.Scatter(x=df['Reported Date'], y=df['Score'],
    mode='markers',
    marker= dict(color=list(map(SetColor, df['Site']))),
    name='Points',
    text="Site: " + df['Site'].map(str) + " " + "Ticket: "+ df['Ticket ID'].map(str)))
</code>```

fig.add_trace(go.Scatter(x=df['Reported Date'], y=df['Score'],
    mode='markers',
    marker_color= df['Site'],
    name='Points',
    text="Site: " + df['Site'].map(str) + " " + "Ticket: "+ df['Ticket ID'].map(str)))
```

I know that Plotly/Dash wants an integer. Is there a work around for this? How can I plot site color in the markers?

答:
I would start with a dictionary mapping colors and sites.

```<code>d = {
    'ABC':'red',
    'DEF':'green',
    'GHI':'black'
}
</code>```

You can use any HTML color name there.

Then, you can make a list of colors based on your dict.

```<code>colors = [d[k] for k in df['Site'].values]
</code>```

Finally, you can pass marker_color=colors to fig.add_trace()

ContentLicense: CC BY-SA 4.0

Body:
Pretty simple question here, but I cannot seem to figure it out. I have a dataframe column with 3 possible values:

print(df['Site'])

0        ABC
1        EFG
2        ABC
3        ABC
4        HIJ

When I plot, each site has the same color, but I would each marker to have a color to represent the site. I have tried to following 2 options with no luck:

fig.add_trace(go.Scatter(x=df['Reported Date'], y=df['Score'],
    mode='markers',
    marker= dict(color=list(map(SetColor, df['Site']))),
    name='Points',
    text="Site: " + df['Site'].map(str) + " " + "Ticket: "+ df['Ticket ID'].map(str)))

fig.add_trace(go.Scatter(x=df['Reported Date'], y=df['Score'],
    mode='markers',
    marker_color= df['Site'],
    name='Points',
    text="Site: " + df['Site'].map(str) + " " + "Ticket: "+ df['Ticket ID'].map(str)))

I know that Plotly/Dash wants an integer. Is there a work around for this? How can I plot site color in the markers?

Body:
I would start with a dictionary mapping colors and sites.

d = {
    'ABC':'red',
    'DEF':'green',
    'GHI':'black'
}

You can use any HTML color name there.

Then, you can make a list of colors based on your dict.

colors = [d[k] for k in df['Site'].values]

Finally, you can pass marker_color=colors to fig.add_trace()


问:
c#: Create new settings at run time
c# windows forms: How do you create new settings at run time so that they are permanently saved as Settings.Default.-- values?</p>

答:
It took me a long time using the top two answers here plus this link (Create new settings on runtime and read after restart) to get it to finally work.

First of all, set your expectations.  The answer here will create a new user setting and you can get its value the next time you launch your app.  However, the setting you created this way will not appear in the Settings designer.  In fact, when you relaunch the app and try to access the setting in your code, it will not find it.  However, the setting you have created through code is saved in the user.config file (say jDoe.config) somewhere in your file system.  For you to access this value, you have to add the setting again.

Here is a working example I have:

```<code>        private void FormPersistence_Load(object sender, EventArgs e)
        {
            StartPosition = FormStartPosition.Manual;
            // Set window location
            var exists = Settings.Default.Properties.OfType<SettingsProperty>().Any(p => p.Name == Name + "Location");
            if (exists)
            {
                this.Location = (Point)Settings.Default[Name + "Location"];
            }
            else
            {
                var property = new SettingsProperty(Settings.Default.Properties["baseLocation"]);
                property.Name = Name + "Location";
                Settings.Default.Properties.Add(property);
                Settings.Default.Reload();
                this.Location = (Point)Settings.Default[Name + "Location"];
            }
        }
</code>```

Note:
My new setting's name will be resolved at run time. Name is really this.Name, which is the form's name. This is a base form that other forms can inherit from, so all the child forms will be able to remember their locations.

baseLocation is a setting I have manually created in Settings designer.  The new setting I have is the same type.  This way I don't have to worry about things like provider, type, etc. in code.

OwnerDisplayName: Paul

LastEditorDisplayName: OregonGhost

ContentLicense: CC BY-SA 2.5

Title: c#: Create new settings at run time

Body:
It took me a long time using the top two answers here plus this link (Create new settings on runtime and read after restart) to get it to finally work.

First of all, set your expectations.  The answer here will create a new user setting and you can get its value the next time you launch your app.  However, the setting you created this way will not appear in the Settings designer.  In fact, when you relaunch the app and try to access the setting in your code, it will not find it.  However, the setting you have created through code is saved in the user.config file (say jDoe.config) somewhere in your file system.  For you to access this value, you have to add the setting again.

Here is a working example I have:

        private void FormPersistence_Load(object sender, EventArgs e)
        {
            StartPosition = FormStartPosition.Manual;
            // Set window location
            var exists = Settings.Default.Properties.OfType<SettingsProperty>().Any(p => p.Name == Name + "Location");
            if (exists)
            {
                this.Location = (Point)Settings.Default[Name + "Location"];
            }
            else
            {
                var property = new SettingsProperty(Settings.Default.Properties["baseLocation"]);
                property.Name = Name + "Location";
                Settings.Default.Properties.Add(property);
                Settings.Default.Reload();
                this.Location = (Point)Settings.Default[Name + "Location"];
            }
        }

Note:
My new setting's name will be resolved at run time. Name is really this.Name, which is the form's name. This is a base form that other forms can inherit from, so all the child forms will be able to remember their locations.

baseLocation is a setting I have manually created in Settings designer.  The new setting I have is the same type.  This way I don't have to worry about things like provider, type, etc. in code.


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答:
Have you tried sp_help?</p>

```<code>sp_help 'TableName'
</code>```

ContentLicense: CC BY-SA 3.0

Title: T-SQL query to show table definition?

Body:
Have you tried sp_help?

sp_help 'TableName'


问:
Spring Boot OAuth Always redirecting to HTTP (IBM Cloud CF + Spring Boot 2)
Using Spring Boot OAuth 2 on IBM Cloud CF Java Buildpack...

https://github.com/ericis/oauth-cf-https-issue

*I have tried every combination of the below.

With this configuration, the application is stuck in an endless loop of redirects, where the OAuth redirect strategy sends it to http and then this configuration sends it to https.

http.requiresChannel().anyRequest().requiresSecure()

Without this configuration, users can login via http (undesired).

Full config:

```<code>http.
  requiresChannel().anyRequest().requiresSecure().
  authorizeRequests().
    // allow access to...
    antMatchers("favicon.ico", "/login", "/loginFailure", "/oauth2/authorization/ghe")
    .permitAll().anyRequest().authenticated().and().oauth2Login().
    // Codify "spring.security.oauth2.client.registration/.provider"
    clientRegistrationRepository(this.clientRegistrationRepository()).
    // setup OAuth2 client service to use clientRegistrationRepository
    authorizedClientService(this.authorizedClientService()).
    successHandler(this.successHandler()).
    // customize login pages
    loginPage("/login").failureUrl("/loginFailure").
    userInfoEndpoint().
      // customize the principal
      userService(this.userService());
</code>```

I've also tried:

Server configuration to use https

```<code>server:
  useForwardHeaders: true
  tomcat:
    protocolHeader: x-forwarded-proto
</code>```

Servlet filter

```<code>import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class HttpToHttpsFilter implements Filter {

  private static final Logger log = LoggerFactory.getLogger(HttpToHttpsFilter.class);

  private static final String HTTP = "http";
  private static final String SCHEME_HTTP = "http://";
  private static final String SCHEME_HTTPS = "https://";
  private static final String LOCAL_ID = "0:0:0:0:0:0:0:1";
  private static final String LOCALHOST = "localhost";

  @Value("${local.ip}")
  private String localIp;

  public HttpToHttpsFilter() {
    // Sonar
  }

  @Override
  public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
      throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;

    final HttpServletResponse response = (HttpServletResponse) res;

    // http, not localhost, not localhost ipv6, not local IP
    if (HTTP.equals(request.getScheme()) &&
        !LOCALHOST.equals(request.getRemoteHost()) &&
        !LOCAL_ID.equals(request.getRemoteHost()) &&
        (this.localIp != null && !this.localIp.equals(request.getRemoteHost()))) {

      final String query = request.getQueryString();

      String oldLocation = request.getRequestURL().toString();

      if (query != null) {
        oldLocation += "?" + query;
      }

      final String newLocation = oldLocation.replaceFirst(SCHEME_HTTP, SCHEME_HTTPS);

      try {

        log.info("HTTP redirect from {} to {} ", oldLocation, newLocation);

        response.sendRedirect(newLocation);

      } catch (IOException e) {
        log.error("Cannot redirect to {} {} ", newLocation, e);
      }
    } else {
      chain.doFilter(req, res);
    }
  }

  @Override
  public void destroy() {
    // Sonar
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
    // Sonar
  }
}
</code>```

Dependencies

```<code>dependencies {

    //
    // BASICS

    // health and monitoring
    // compile('org.springframework.boot:spring-boot-starter-actuator')

    // security
    compile('org.springframework.boot:spring-boot-starter-security')

    // configuration
    compile('org.springframework.boot:spring-boot-configuration-processor')

  //
  // WEB

  // web
  compile('org.springframework.boot:spring-boot-starter-web')

  // thymeleaf view render
  compile('org.springframework.boot:spring-boot-starter-thymeleaf')

  // thymeleaf security extras
  compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4')

  //
  // OAUTH

  // OAuth client
  compile('org.springframework.security:spring-security-oauth2-client')

  // OAuth lib
  compile('org.springframework.security:spring-security-oauth2-jose')

  // OAuth config
  compile('org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.0.RELEASE')

  //
  // CLOUD

  // cloud connectors (e.g. vcaps)
  compile('org.springframework.boot:spring-boot-starter-cloud-connectors')

    //
    // TOOLS

    runtime('org.springframework.boot:spring-boot-devtools')

    //
    // TEST

    // test
    testCompile('org.springframework.boot:spring-boot-starter-test')

    // security test
    testCompile('org.springframework.security:spring-security-test')
}
</code>```

答:
Because of using Spring 5, decided to go with next solution (security configuration):

```<code>        http
            .addFilterBefore(new ForwardedHeaderFilter(), OAuth2AuthorizationRequestRedirectFilter.class)
</code>```

x-forwarded-* header parameters handled correct now.

Body:
Using Spring Boot OAuth 2 on IBM Cloud CF Java Buildpack...

https://github.com/ericis/oauth-cf-https-issue

*I have tried every combination of the below.

With this configuration, the application is stuck in an endless loop of redirects, where the OAuth redirect strategy sends it to http and then this configuration sends it to https.

http.requiresChannel().anyRequest().requiresSecure()

Without this configuration, users can login via http (undesired).

Full config:

http.
  requiresChannel().anyRequest().requiresSecure().
  authorizeRequests().
    // allow access to...
    antMatchers("favicon.ico", "/login", "/loginFailure", "/oauth2/authorization/ghe")
    .permitAll().anyRequest().authenticated().and().oauth2Login().
    // Codify "spring.security.oauth2.client.registration/.provider"
    clientRegistrationRepository(this.clientRegistrationRepository()).
    // setup OAuth2 client service to use clientRegistrationRepository
    authorizedClientService(this.authorizedClientService()).
    successHandler(this.successHandler()).
    // customize login pages
    loginPage("/login").failureUrl("/loginFailure").
    userInfoEndpoint().
      // customize the principal
      userService(this.userService());

I've also tried:

Server configuration to use https

server:
  useForwardHeaders: true
  tomcat:
    protocolHeader: x-forwarded-proto

Servlet filter

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class HttpToHttpsFilter implements Filter {

  private static final Logger log = LoggerFactory.getLogger(HttpToHttpsFilter.class);

  private static final String HTTP = "http";
  private static final String SCHEME_HTTP = "http://";
  private static final String SCHEME_HTTPS = "https://";
  private static final String LOCAL_ID = "0:0:0:0:0:0:0:1";
  private static final String LOCALHOST = "localhost";

  @Value("${local.ip}")
  private String localIp;

  public HttpToHttpsFilter() {
    // Sonar
  }

  @Override
  public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
      throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;

    final HttpServletResponse response = (HttpServletResponse) res;

    // http, not localhost, not localhost ipv6, not local IP
    if (HTTP.equals(request.getScheme()) &&
        !LOCALHOST.equals(request.getRemoteHost()) &&
        !LOCAL_ID.equals(request.getRemoteHost()) &&
        (this.localIp != null && !this.localIp.equals(request.getRemoteHost()))) {

      final String query = request.getQueryString();

      String oldLocation = request.getRequestURL().toString();

      if (query != null) {
        oldLocation += "?" + query;
      }

      final String newLocation = oldLocation.replaceFirst(SCHEME_HTTP, SCHEME_HTTPS);

      try {

        log.info("HTTP redirect from {} to {} ", oldLocation, newLocation);

        response.sendRedirect(newLocation);

      } catch (IOException e) {
        log.error("Cannot redirect to {} {} ", newLocation, e);
      }
    } else {
      chain.doFilter(req, res);
    }
  }

  @Override
  public void destroy() {
    // Sonar
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
    // Sonar
  }
}

Dependencies

dependencies {

    //
    // BASICS

    // health and monitoring
    // compile('org.springframework.boot:spring-boot-starter-actuator')

    // security
    compile('org.springframework.boot:spring-boot-starter-security')

    // configuration
    compile('org.springframework.boot:spring-boot-configuration-processor')

  //
  // WEB

  // web
  compile('org.springframework.boot:spring-boot-starter-web')

  // thymeleaf view render
  compile('org.springframework.boot:spring-boot-starter-thymeleaf')

  // thymeleaf security extras
  compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4')

  //
  // OAUTH

  // OAuth client
  compile('org.springframework.security:spring-security-oauth2-client')

  // OAuth lib
  compile('org.springframework.security:spring-security-oauth2-jose')

  // OAuth config
  compile('org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.0.RELEASE')

  //
  // CLOUD

  // cloud connectors (e.g. vcaps)
  compile('org.springframework.boot:spring-boot-starter-cloud-connectors')

    //
    // TOOLS

    runtime('org.springframework.boot:spring-boot-devtools')

    //
    // TEST

    // test
    testCompile('org.springframework.boot:spring-boot-starter-test')

    // security test
    testCompile('org.springframework.security:spring-security-test')
}

Body:
Because of using Spring 5, decided to go with next solution (security configuration):

        http
            .addFilterBefore(new ForwardedHeaderFilter(), OAuth2AuthorizationRequestRedirectFilter.class)

x-forwarded-* header parameters handled correct now.


问:
delete without a head pointer
Question:
You are given a certain node somewhere in the middle of the linked list and you need to delete that node.
You are not given the head node to the linked list.
Condition: the given node has atleast one node next to it.

The structure of the node:

```<code>struct Node {
  int data;
  struct Node *next;
  Node(int x) {
    data = x;
    next = NULL;
  }
}*head;
</code>```

My solution:

```<code>Node* temp=node->next;
node->data=node->next->data;
node->next=node->next->next;
delete temp;
</code>```

Another solution(that i didn't understand):

```<code>Node *temp = node->next;
*node = *(node->next);
delete temp;
</code>```

Both give correct results but i did not understand the 2nd line of the latter solution.

答:
The struct Node has a default copy assignment since neither it nor a move assignment is declared.

So *node = *(node->next); copies both attributes (data and next) from *(node->next) to *node making it exactly the same as:

```<code>(*node).data = (*(node->next)).data
(*node).next = (*(node->next)).next
</code>```

Title: delete without a head pointer

Body:
Question:
You are given a certain node somewhere in the middle of the linked list and you need to delete that node.
You are not given the head node to the linked list.
Condition: the given node has atleast one node next to it.

The structure of the node:

struct Node {
  int data;
  struct Node *next;
  Node(int x) {
    data = x;
    next = NULL;
  }
}*head;

My solution:

Node* temp=node->next;
node->data=node->next->data;
node->next=node->next->next;
delete temp;

Another solution(that i didn't understand):

Node *temp = node->next;
*node = *(node->next);
delete temp;

Both give correct results but i did not understand the 2nd line of the latter solution.

Body:
The struct Node has a default copy assignment since neither it nor a move assignment is declared.

So *node = *(node->next); copies both attributes (data and next) from *(node->next) to *node making it exactly the same as:

(*node).data = (*(node->next)).data
(*node).next = (*(node->next)).next


问:
Trouble implementing parallax background with IntersectionObserver
I'm trying to use IntersectionObserver to implement a parallax background scroll effect. I'm not quite sure what combination of threshhold and intersection ratio will allow a continuous effect while the element is either fully or partially in view (it should stop when the element is fully out of view).  I can only get the effect to happen while the element is "intersecting" either the top or the bottom of the viewport.  Here are two attempts I made:

I got close to what I want, but when the element is fully in the viewport, there is no parallax. The parallax effect only happens when the element is partially above or below the screen:

```<code>function observe(selector, threshold, callback) {
  const elements = document.querySelectorAll(selector);
  const options = { rootMargin: '0px', threshold: threshold };
  const observer = new IntersectionObserver(callback, options);
  for (const element of elements) {
    observer.observe(element);
  }
}
function parallax(entries, observer) {
  var scroll, yScroll, elementTop;
  for (const entry of entries) {
  if (entry.isIntersecting) {
      scroll = $(window).scrollTop();
      elementTop = $(entry.target).offset().top;
      yScroll = .5*(scroll - elementTop) + "px";
      $(entry.target).css({"background-position": "50% calc(50% + " + yScroll + ")"});
    }
  }
}
function createThreshold() {
  const threshold = [];
  for (let i = 0; i <= 1.0; i += 0.01) {
    threshold.push(i);
  }
  return threshold;
}
const threshold = createThreshold();
observe('.parallax-bg', threshold, parallax);
</code>```

Link to fiddle of this attempt: https://jsfiddle.net/pgb9hske/

I also realize that using things like $(window).scrollTop() might possibly be defeating the purpose of using intersection observer, but I couldn't figure out a way to use the intersectionRatio in a math equation to implement the parallax.  I'll worry about that later, I just want to get the effect working when the element is completely in the viewport for now.

Here was another attempt, but it's not even close.  The background position just "jumps" when the element crosses the top or bottom of the viewport.

```<code>const parallax_bgs = document.querySelectorAll('.parallax-bg');
const parallaxConfig = { root: null, rootMargin: '0px 0px', threshold: 0 };
parallaxObserver = new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.intersectionRatio > 0) {
      scroll = $(window).scrollTop();
      elementTop = $(entry.target).offset().top;
      yScroll = .5*(scroll - elementTop) + "px";
      $(entry.target).css({"background-position": "50% calc(50% + " + yScroll + ")"});
    }
  });
}, parallaxConfig);
parallax_bgs.forEach(function (element) {
  parallaxObserver.observe(element);
});
</code>```

Any help is greatly appreciated.

答:
I worked around this problem by nesting an element inside the parallax background container.

e.g.

```<code><div class="parallax-banner">
<div class="parallax-intersector"></div>
</div>
</code>```

and then applying this scss

```<code>.parallax-banner {
    height: 800px;
    position: relative;

    .parallax-intersector {
        width: 10px;
        position: absolute;
        left: 0;
        bottom: 50%;
        height: 100vh;
        min-height: 800px;  // the min-height must match the height of your container
        background: #f00;
        z-index: 10;
        transform: translateY(50%);
        opacity: 0;
    }
}

</code>```

This gives an element that will always be at least the size of the viewport.

You can then target this element in your intersection observer.

The intersection target element will, when the viewport is larger than your element, start and end above and below your banner, with the offset being equal above and below.

You just need to factor that into your background position calculation.

e.g.

```<code>let factor = 20;
let offset = (window.innerHeight - entry.target.parentElement.getBoundingClientRect().height) / 2;
let elapsedPx = (entry.target.getBoundingClientRect().y - window.innerHeight) + offset;
let yScroll = entry.target.parentElement.offsetTop + parseInt(elapsedPx / factor);

</code>```

See example -> https://codepen.io/nxtds/pen/Rwrwbrx

Body:
I'm trying to use IntersectionObserver to implement a parallax background scroll effect. I'm not quite sure what combination of threshhold and intersection ratio will allow a continuous effect while the element is either fully or partially in view (it should stop when the element is fully out of view).  I can only get the effect to happen while the element is "intersecting" either the top or the bottom of the viewport.  Here are two attempts I made:

I got close to what I want, but when the element is fully in the viewport, there is no parallax. The parallax effect only happens when the element is partially above or below the screen:

function observe(selector, threshold, callback) {
  const elements = document.querySelectorAll(selector);
  const options = { rootMargin: '0px', threshold: threshold };
  const observer = new IntersectionObserver(callback, options);
  for (const element of elements) {
    observer.observe(element);
  }
}
function parallax(entries, observer) {
  var scroll, yScroll, elementTop;
  for (const entry of entries) {
  if (entry.isIntersecting) {
      scroll = $(window).scrollTop();
      elementTop = $(entry.target).offset().top;
      yScroll = .5*(scroll - elementTop) + "px";
      $(entry.target).css({"background-position": "50% calc(50% + " + yScroll + ")"});
    }
  }
}
function createThreshold() {
  const threshold = [];
  for (let i = 0; i <= 1.0; i += 0.01) {
    threshold.push(i);
  }
  return threshold;
}
const threshold = createThreshold();
observe('.parallax-bg', threshold, parallax);

Link to fiddle of this attempt: https://jsfiddle.net/pgb9hske/

I also realize that using things like $(window).scrollTop() might possibly be defeating the purpose of using intersection observer, but I couldn't figure out a way to use the intersectionRatio in a math equation to implement the parallax.  I'll worry about that later, I just want to get the effect working when the element is completely in the viewport for now.

Here was another attempt, but it's not even close.  The background position just "jumps" when the element crosses the top or bottom of the viewport.

const parallax_bgs = document.querySelectorAll('.parallax-bg');
const parallaxConfig = { root: null, rootMargin: '0px 0px', threshold: 0 };
parallaxObserver = new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.intersectionRatio > 0) {
      scroll = $(window).scrollTop();
      elementTop = $(entry.target).offset().top;
      yScroll = .5*(scroll - elementTop) + "px";
      $(entry.target).css({"background-position": "50% calc(50% + " + yScroll + ")"});
    }
  });
}, parallaxConfig);
parallax_bgs.forEach(function (element) {
  parallaxObserver.observe(element);
});

Any help is greatly appreciated.

Body:
I worked around this problem by nesting an element inside the parallax background container.

e.g.

<div class="parallax-banner">
<div class="parallax-intersector"></div>
</div>

and then applying this scss

.parallax-banner {
    height: 800px;
    position: relative;

    .parallax-intersector {
        width: 10px;
        position: absolute;
        left: 0;
        bottom: 50%;
        height: 100vh;
        min-height: 800px;  // the min-height must match the height of your container
        background: #f00;
        z-index: 10;
        transform: translateY(50%);
        opacity: 0;
    }
}

This gives an element that will always be at least the size of the viewport.

You can then target this element in your intersection observer.

The intersection target element will, when the viewport is larger than your element, start and end above and below your banner, with the offset being equal above and below.

You just need to factor that into your background position calculation.

e.g.

let factor = 20;
let offset = (window.innerHeight - entry.target.parentElement.getBoundingClientRect().height) / 2;
let elapsedPx = (entry.target.getBoundingClientRect().y - window.innerHeight) + offset;
let yScroll = entry.target.parentElement.offsetTop + parseInt(elapsedPx / factor);

See example -> https://codepen.io/nxtds/pen/Rwrwbrx


问:
How to dynamic inventory from gcp acount using ansible?
Just started with ansible, how do i pull dynamic inventory from my gcp account using ansible?

any kind of example config file will be appreciated. Thanks!

答:
There is a plugin for ansible named gcp_compute that you could use to discover all your resources from GCP and being shown in Ansible Inventory.

I also found an Ansible documentation which will guide you to implement GCP and Ansible.


问:
How to build mysql docker image with custom value for max_allowed_packet?
How to build mysql docker image with custom value for max_allowed_packet?

```<code>#my-custom.cnf
[mysqld]
max_allowed_packet=64M
</code>```

```<code>#Dockerfile
FROM mysql/mysql-server:5.7
RUN echo "Custom mysql build"
COPY ./my-custom.cnf /etc/mysql/conf.d/
RUN echo "Listing customized configurations" && cat /etc/mysql/conf.d/lj-mysql.conf
</code>```

The customized mysql container still shows 4MB only.

```<code>mysql> show variables like '%max_allowed_packet%';
+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| max_allowed_packet       | 4194304    |
| slave_max_allowed_packet | 1073741824 |
+--------------------------+------------+
</code>```

Any suggestions?

答:
You should use docker volume for such purposes. Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

```<code>docker run -d -v ./my-custom.cnf:/etc/mysql/conf.d/ mysql/mysql-server
</code>```

This will mount your local config on your host machine into docker container and will run mysql in detached mode.

Body:
How to build mysql docker image with custom value for max_allowed_packet?

#my-custom.cnf
[mysqld]
max_allowed_packet=64M

#Dockerfile
FROM mysql/mysql-server:5.7
RUN echo "Custom mysql build"
COPY ./my-custom.cnf /etc/mysql/conf.d/
RUN echo "Listing customized configurations" && cat /etc/mysql/conf.d/lj-mysql.conf

The customized mysql container still shows 4MB only.

mysql> show variables like '%max_allowed_packet%';
+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| max_allowed_packet       | 4194304    |
| slave_max_allowed_packet | 1073741824 |
+--------------------------+------------+

Any suggestions?

Body:
You should use docker volume for such purposes. Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

docker run -d -v ./my-custom.cnf:/etc/mysql/conf.d/ mysql/mysql-server

This will mount your local config on your host machine into docker container and will run mysql in detached mode.


问:
Javascript charting and link-able labels
Any ideas of a JavaScript charting library that allows me to use data labels that I can double as HTML links? I need to be able to create radar charts, specifically, and other charts would be a plus.</p>

答: We are using Flot charting library with a plugin that enables radar graphing.</p>


问:
Unable to create a Rails app due to incompatible library version - load error
First-time post here! I am trying to build a rails app but I am having a ton of difficulty getting started. I have installed Rails, and Ruby but every time I go to make the app (Miless-MBP:railstest miles$ rails new tester2) I get a multitude of errors. The full log is below, but I have listed the 4 here.

Thank you all so much!

```<code>/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)
</code>```

```<code>    26: from bin/rails:3:in `<main>'
    25: from bin/rails:3:in `load'
    24: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    23: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    17: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    16: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    15: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    14: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    13: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    12: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:40:in `with_gems'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `<top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)
    27: from bin/rails:3:in `<main>'
    26: from bin/rails:3:in `load'
    25: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    24: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    23: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    17: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    16: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    15: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    14: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    13: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    12: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:40:in `with_gems'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:8:in `<top (required)>'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `rescue in <top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)
    27: from bin/rails:3:in `<main>'
    26: from bin/rails:3:in `load'
    25: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    24: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    23: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    17: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    16: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    15: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    14: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    13: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    12: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:39:in `with_gems'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:43:in `rescue in with_gems'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `<top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)
    28: from bin/rails:3:in `<main>'
    27: from bin/rails:3:in `load'
    26: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    25: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    24: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    23: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    17: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    16: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    15: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    14: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    13: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    12: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:39:in `with_gems'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:43:in `rescue in with_gems'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:8:in `<top (required)>'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `rescue in <top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)```

```

答:
I had the same issue. You need to completely clean out the msgpack gem using:

```<code>gem uninstall msgpack
</code>```

Then reinstall it, so that the libraries are built against the version of ruby you're now using.

You could also try:

```<code>bundle install --redownload
</code>```

which should reinstall the gems and rebuild the linked libraries with the version of ruby you're now using.

Body:
First-time post here! I am trying to build a rails app but I am having a ton of difficulty getting started. I have installed Rails, and Ruby but every time I go to make the app (Miless-MBP:railstest miles$ rails new tester2) I get a multitude of errors. The full log is below, but I have listed the 4 here.

Thank you all so much!

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)

/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)

    26: from bin/rails:3:in `'
    25: from bin/rails:3:in `load'
    24: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    23: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    17: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    16: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    15: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    14: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    13: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    12: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:40:in `with_gems'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `<top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)
    27: from bin/rails:3:in `'
    26: from bin/rails:3:in `load'
    25: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    24: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    23: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    17: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    16: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    15: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    14: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    13: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    12: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:40:in `with_gems'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:8:in `<top (required)>'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `rescue in <top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)
    27: from bin/rails:3:in `'
    26: from bin/rails:3:in `load'
    25: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    24: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    23: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    17: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    16: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    15: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    14: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    13: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    12: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:39:in `with_gems'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:43:in `rescue in with_gems'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `<top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:9:in `require': cannot load such file -- msgpack/2.6/msgpack (LoadError)
    28: from bin/rails:3:in `'
    27: from bin/rails:3:in `load'
    26: from /Users/miles/railstest/tester2/bin/spring:15:in `<top (required)>'
    25: from /Users/miles/railstest/tester2/bin/spring:15:in `require'
    24: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `<top (required)>'
    23: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/binstub.rb:11:in `load'
    22: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/bin/spring:49:in `<top (required)>'
    21: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client.rb:30:in `run'
    20: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/command.rb:7:in `call'
    19: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `call'
    18: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in `load'
    17: from /Users/miles/railstest/tester2/bin/rails:8:in `<top (required)>'
    16: from /Users/miles/railstest/tester2/bin/rails:8:in `require_relative'
    15: from /Users/miles/railstest/tester2/config/boot.rb:4:in `<top (required)>'
    14: from /Users/miles/railstest/tester2/config/boot.rb:4:in `require'
    13: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `<top (required)>'
    12: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/setup.rb:1:in `require_relative'
    11: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `<top (required)>'
    10: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap.rb:3:in `require_relative'
     9: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `<top (required)>'
     8: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache.rb:74:in `require_relative'
     7: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `<top (required)>'
     6: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:39:in `with_gems'
     5: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/explicit_require.rb:43:in `rescue in with_gems'
     4: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `block in <top (required)>'
     3: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/store.rb:3:in `require'
     2: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:8:in `<top (required)>'
     1: from /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `rescue in <top (required)>'
/Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack.rb:11:in `require': incompatible library version - /Users/miles/.rvm/gems/ruby-2.6.3/gems/msgpack-1.3.1/lib/msgpack/msgpack.bundle (LoadError)```

Body:
I had the same issue. You need to completely clean out the msgpack gem using:

gem uninstall msgpack

Then reinstall it, so that the libraries are built against the version of ruby you're now using.

You could also try:

bundle install --redownload

which should reinstall the gems and rebuild the linked libraries with the version of ruby you're now using.


问:
Cross Origin Resource Sharing error while making put request in nodejs
I got this error while making put request.

Access to XMLHttpRequest at
  'http://localhost:5000/api/products/undefined' from origin
  'http://localhost:3000' has been blocked by CORS policy: Method PUT is
  not allowed by Access-Control-Allow-Methods in preflight response.

I have even included CORS policy in main server file

```<code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization",
    "Access-Control-Allow-Methods","GET, PUT, POST, OPTIONS"
  );
  next();
});
</code>```

答:
It looks like the header function should receive only two parameters at a time:

```<code>app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
    next();
});
</code>```

For more details on how to enable CORS on ExpressJS see this reference:
https://enable-cors.org/server_expressjs.html

You can use a npm package, this package is a middleware, to install it just do:

```<code>npm install cors
</code>```

And to use it:

```<code>var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
</code>```

For details on how to use the cors package refers to this documentation: https://expressjs.com/en/resources/middleware/cors.html

Body:
I got this error while making put request.

Access to XMLHttpRequest at
  'http://localhost:5000/api/products/undefined' from origin
  'http://localhost:3000' has been blocked by CORS policy: Method PUT is
  not allowed by Access-Control-Allow-Methods in preflight response.

I have even included CORS policy in main server file

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization",
    "Access-Control-Allow-Methods","GET, PUT, POST, OPTIONS"
  );
  next();
});

Body:
It looks like the header function should receive only two parameters at a time:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
    next();
});

For more details on how to enable CORS on ExpressJS see this reference:
https://enable-cors.org/server_expressjs.html

You can use a npm package, this package is a middleware, to install it just do:

npm install cors

And to use it:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

For details on how to use the cors package refers to this documentation: https://expressjs.com/en/resources/middleware/cors.html


问:
Created kestrel service on Ubuntu stopped with error (code=exited, status=200/CHDIR)
I create a service in /etc/systemd/system as follow :

```<code>$ cd /etc/systemd/system
$ sudo nano test.service
</code>```

Add the following content

```<code>[Unit]
Description=test app

[Service]
WorkingDirectory=/var/www/test-app
ExecStart=/usr/bin/dotnet /var/www/test-app/Test.App.dll
Restart=always
RestartSec=10
SyslogIdentifier=test
User=ubuntu
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target
</code>```

after save the service
run following commands

```<code>$ sudo systemctl enable test.service
$ sudo systemctl start test.service
$ sudo systemctl status test.service
</code>```

but display this error

```<code>test.service - test app
   Loaded: loaded (/etc/systemd/system/test.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: exit-code) since Sat 2020-02-15 10:41:19 UTC; 8s ago
  Process: 24631 ExecStart=/usr/bin/dotnet /var/www/test-app/Test.App.dll (code=exited, status=200/CHDIR)
 Main PID: 24631 (code=exited, status=200/CHDIR)
</code>```

The user (ubuntu) is exist and have proper ownership of the app's files

答: I had the same exact issue. I tried permissions, path length, using different directories. But the issue was a small mistake in the Working Directory path. Fixed, and all worked well.</p>

Body:
I create a service in /etc/systemd/system as follow :

$ cd /etc/systemd/system
$ sudo nano test.service

Add the following content

[Unit]
Description=test app

[Service]
WorkingDirectory=/var/www/test-app
ExecStart=/usr/bin/dotnet /var/www/test-app/Test.App.dll
Restart=always
RestartSec=10
SyslogIdentifier=test
User=ubuntu
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

after save the service
run following commands

$ sudo systemctl enable test.service
$ sudo systemctl start test.service
$ sudo systemctl status test.service

but display this error

test.service - test app
   Loaded: loaded (/etc/systemd/system/test.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: exit-code) since Sat 2020-02-15 10:41:19 UTC; 8s ago
  Process: 24631 ExecStart=/usr/bin/dotnet /var/www/test-app/Test.App.dll (code=exited, status=200/CHDIR)
 Main PID: 24631 (code=exited, status=200/CHDIR)

The user (ubuntu) is exist and have proper ownership of the app's files


问:
How to select unique pairs in SQL Server according to the third parameter?
I have the test table with three columns Fir, Sec and Val.

```<code>Fir    Sec     Val
------------------
A       A       1
A       B       7
A       C       31
B       A       3
B       D       4
B       F       7
C       X       10
C       Y       10
C       Z       9
</code>```

I am trying to extract all the unique values of Fir with a minimum alphabetical value of Sec which corresponds to the maximum value of Val.

For a given text table, the output must be

```<code>Fir    Sec
----------
A       C
B       F
C       X
</code>```

I manage this somehow with the script below, but I think there should be an simpler solution to produce the same result.

SELECT
    Fir, MIN(Sec) AS Sec
FROM
    (SELECT
         a.Fir, b.Sec, MaxVal
     FROM
         (SELECT
              Fir, MAX(Val) AS MaxVal
          FROM
              Test3
          GROUP BY
              Fir) a
     LEFT OUTER JOIN
         Test3 b ON a.Fir = b.Fir AND a.MaxVal = b.Val) c
GROUP BY
    Fir
ORDER BY
    Fir
```

<p>Any suggestion to improve this would be appreciated.</p>

<p>Code to generate sample data:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE Test3
(
    Fir CHAR(5),
    Sec CHAR(5),
    Val INT
)

INSERT INTO Test3
VALUES ('A', 'A', 1), ('A', 'B', 7), ('A', 'C', 31),
       ('B', 'A', 3), ('B', 'D', 4), ('B', 'F', 7),
       ('C', 'X', 10), ('C', 'Y', 10), ('C', 'Z', 9)
</code>```

答:
I'll bite; this method uses ROW_NUMBER() to do the heavy-lifting:

```<code>WITH x AS (
    SELECT
        Fir,
        Sec,
        ROW_NUMBER() OVER (PARTITION BY Fir ORDER BY Val DESC, Sec ASC) AS order_id
    FROM
        Test3)
SELECT
    Fir,
    Sec
FROM
    x
WHERE
    order_id = 1;
</code>```

Body:
I have the test table with three columns Fir, Sec and Val.

Fir    Sec     Val
------------------
A       A       1
A       B       7
A       C       31
B       A       3
B       D       4
B       F       7
C       X       10
C       Y       10
C       Z       9

I am trying to extract all the unique values of Fir with a minimum alphabetical value of Sec which corresponds to the maximum value of Val.

For a given text table, the output must be

Fir    Sec
----------
A       C
B       F
C       X

I manage this somehow with the script below, but I think there should be an simpler solution to produce the same result.

SELECT
    Fir, MIN(Sec) AS Sec
FROM
    (SELECT
         a.Fir, b.Sec, MaxVal
     FROM
         (SELECT
              Fir, MAX(Val) AS MaxVal
          FROM
              Test3
          GROUP BY
              Fir) a
     LEFT OUTER JOIN
         Test3 b ON a.Fir = b.Fir AND a.MaxVal = b.Val) c
GROUP BY
    Fir
ORDER BY
    Fir

Any suggestion to improve this would be appreciated.

Code to generate sample data:

CREATE TABLE Test3
(
    Fir CHAR(5),
    Sec CHAR(5),
    Val INT
)

INSERT INTO Test3
VALUES ('A', 'A', 1), ('A', 'B', 7), ('A', 'C', 31),
       ('B', 'A', 3), ('B', 'D', 4), ('B', 'F', 7),
       ('C', 'X', 10), ('C', 'Y', 10), ('C', 'Z', 9)

Body:
I'll bite; this method uses ROW_NUMBER() to do the heavy-lifting:

WITH x AS (
    SELECT
        Fir,
        Sec,
        ROW_NUMBER() OVER (PARTITION BY Fir ORDER BY Val DESC, Sec ASC) AS order_id
    FROM
        Test3)
SELECT
    Fir,
    Sec
FROM
    x
WHERE
    order_id = 1;


问:
Boxplots with the statistical (wilcoxon) test
I have to compare different ML algorithms using caret R package and then find the significance difference between each of these algorithms.

For instance, I am using my code as follows

```<code>nnet2 <- train(result ~ ., data = tr,
              method = "nnet",
               tuneLength = 15,
              metric = "MAE",
              preProc = c("center", "scale", "nzv"),
              trControl = ctrl)

getTrainPerf(nnet2)

svm2 <- train(result ~ ., data = tr,
             method = "svmRadial",

             tuneLength = 15,
             metric = "MAE",
             preProc = c("center", "scale", "nzv"),
             trControl = ctrl)

getTrainPerf(svm2)
</code>```

and few other algorithms like that. Then I have performed wilcoxon test

```<code>wilcox.test (nnet2$resample$MAE, svm2$resample$MAE, paired=T)
</code>```

My question is how can we put the results of the wilcoxon tests as a boxplot in R language?

Thanks

答:
Using an example dataset:

```<code>library(caret)
library(mlbench)
library(ggpubr)
data(BostonHousing)
tr = BostonHousing

ctrl = trainControl(method="cv",number=10)

nnet2 <- train(medv ~ ., data = tr,
              method = "nnet",
               tuneLength = 5,
              metric = "MAE",
              preProc = c("center", "scale", "nzv"),
              trControl = ctrl)

svm2 <- train(medv ~ ., data = tr,
             method = "svmRadial",

             tuneLength = 5,
             metric = "MAE",
             preProc = c("center", "scale", "nzv"),
             trControl = ctrl)
</code>```

Better to create a data.frame, with the MAE and a vector representing the model:

```<code>df = data.frame(MAE=c(nnet2$resample$MAE,svm2$resample$MAE),
model=rep(c("nnet","svm"),each=length(svm2$resample$MAE)))

ggboxplot(df, x = "model",y= "MAE",col="model",palette = c("#00AFBB", "#E7B800")) +
stat_compare_means()
</code>```

Body:
I have to compare different ML algorithms using caret R package and then find the significance difference between each of these algorithms.

For instance, I am using my code as follows

nnet2 <- train(result ~ ., data = tr,
              method = "nnet",
               tuneLength = 15,
              metric = "MAE",
              preProc = c("center", "scale", "nzv"),
              trControl = ctrl)

getTrainPerf(nnet2)

svm2 <- train(result ~ ., data = tr,
             method = "svmRadial",

             tuneLength = 15,
             metric = "MAE",
             preProc = c("center", "scale", "nzv"),
             trControl = ctrl)

getTrainPerf(svm2)

and few other algorithms like that. Then I have performed wilcoxon test

wilcox.test (nnet2$resample$MAE, svm2$resample$MAE, paired=T)

My question is how can we put the results of the wilcoxon tests as a boxplot in R language?

Thanks

Body:
Using an example dataset:

library(caret)
library(mlbench)
library(ggpubr)
data(BostonHousing)
tr = BostonHousing

ctrl = trainControl(method="cv",number=10)

nnet2 <- train(medv ~ ., data = tr,
              method = "nnet",
               tuneLength = 5,
              metric = "MAE",
              preProc = c("center", "scale", "nzv"),
              trControl = ctrl)

svm2 <- train(medv ~ ., data = tr,
             method = "svmRadial",

             tuneLength = 5,
             metric = "MAE",
             preProc = c("center", "scale", "nzv"),
             trControl = ctrl)

Better to create a data.frame, with the MAE and a vector representing the model:

df = data.frame(MAE=c(nnet2$resample$MAE,svm2$resample$MAE),
model=rep(c("nnet","svm"),each=length(svm2$resample$MAE)))

ggboxplot(df, x = "model",y= "MAE",col="model",palette = c("#00AFBB", "#E7B800")) +
stat_compare_means()


问:
HTML5 | Datepicker only 5 days ahead in future
I have a date picker on my web app, I only want the user to be able to click on a date between today and over 5 days (so today the date is 2020-06-02, the user should only be able to click on dates between 2020-06-02 and 2020-06-06).
I have looked for solutions but the only thing I found was using a min and a max, but those do not work for me.
Has anyone an idea how I can achieve this?

This is my code:

```<code><div>
    <form method="post">
        <label for="name">Locatie: </label><br />
        <input type="text" id="naam" asp-for="Locatie" />
        <label for="Datetime">Datum: </label>
        <input value="05-19-2020T12:00" min="05-19-2020T12:00" type="datetime-local" id="DateTime" asp-for="DatumTijd" />
        <input type="submit" value="Submit" />
    </form>
</div>
</code>```

The min and the value both do not work, but it is what I have tried so thats why I am showing this.

答:
Try using minDate and maxDate:

```<code>$( function() {
    $( "#datepicker" ).datepicker({
        minDate: 0,
        maxDate: "+5D"
    });
});
</code>```

Body:
I have a date picker on my web app, I only want the user to be able to click on a date between today and over 5 days (so today the date is 2020-06-02, the user should only be able to click on dates between 2020-06-02 and 2020-06-06).
I have looked for solutions but the only thing I found was using a min and a max, but those do not work for me.
Has anyone an idea how I can achieve this?

This is my code:

    <form method="post">
        Locatie:

        <input type="text" id="naam" asp-for="Locatie" />
        Datum:
        <input value="05-19-2020T12:00" min="05-19-2020T12:00" type="datetime-local" id="DateTime" asp-for="DatumTijd" />
        <input type="submit" value="Submit" />
    </form>

The min and the value both do not work, but it is what I have tried so thats why I am showing this.

Body:
Try using minDate and maxDate:

$( function() {
    $( "#datepicker" ).datepicker({
        minDate: 0,
        maxDate: "+5D"
    });
});


问:
numpy works well in Jupyter Notebook, but not in command line
I am trying to schedule my py file in command line, it has been tested in jupyter notebook, and the ipynb file works well. But when the py file runs in command line, it shows the problem:

Traceback (most recent call last):
  File "test_np.py", line 9, in <module>
    import numpy as np
  File "C:\Users\xxx\Anaconda3\lib\site-packages\numpy\__init__.py", line 140, in <module>
    from . import _distributor_init
  File "C:\Users\xxx\Anaconda3\lib\site-packages\numpy\_distributor_init.py", line 34, in <module>
    from . import _mklinit
ImportError: DLL load failed: The specified module could not be found.

I have investigated the problem, and found one of the similar problem from link, but my Anaconda3 has been installed under Users\xxx\Anaconda3. I am wondering:

1. Whether the path variables is the reason of the problem?

2. If it is, should the Anaconda3 been reinstalled under ProgramData?

3. If the path variables isn't the reason, what is the possible reason?

Thanks.

答:
It seems this problem caused by the path variables .  It has been soved by:

adding 5 variables as below to PATH variables:

\anaconda3

\anaconda3\Library\mingw-64t

\anaconda3\Library\usr\bin

\anaconda3\Library\bin

\anaconda3\Scripts


问:
Quarkus - modify JSESSIONID attributes
Is there a way to add SameSite=None attribute to JSSESSIONID cookie. I tried to add exists(%{o,Set-Cookie}) and regex(pattern="JSESSIONID", value="%{o,Set-Cookie}") -> set(attribute='%{o,Set-Cookie}', value='%{o,Set-Cookie}; Secure; SameSite=None') in undertow-handlers.conf but it looks like this handler is executed before Set-Cookie: JSESSIONID header is set.

答:
I found the solution. It is not very clean but it works. First I've copied three classes from undertow sources.
CookieSameSiteMode.java, SameSiteCookieHandler.java and SameSiteNoneIncompatibleClientChecker.java.
Next I changed setting of sameSiteMode property because implementation of setSameSiteMode throws exception when value is not equal to "lax" or "strict" so I've to use reflection to set field value directly. Next I've added undertow-handlers.conf in META-INF directory with content
samesite-cookie(mode='None', add-secure-for-none=true).
Finally I've added io.undertow.server.handlers.builder.HandlerBuilder file in META-INF/services directory in which I registered my handler. Full example is available on my github

Title: Quarkus - modify JSESSIONID attributes


问:
Search in belongsToMany-relation for item by pivot value
I got these models:

Order

Invoice

An Order can have many Invoices and an Invoice can belong to many Orders.

Example:

Orders:

Order #1

Order #2

Order #3

Invoices:

Invoice #1 -> belongs To Order #1 and Order #2 (so this Invoice contains both Orders)

Invoice #2 -> belongsTo  Order #2 and Order #3

Each belongsTo-relation saves a date as pivot, which defines the last date this order has been invoiced.

Now I'd like to create a isInvoiceable() getter for my Order-Model, which returns, whether the order has been invoiced within the last month or not. If the latest date is older than one month, return true, as this Order should create a new invoice.

So now I need your help: I need to check all invoices, whether there's an Order (belongsToMany) with the order_id of the current Order, and a date-pivot that's older than now - one month. I need to check the order_id because the Invoice could possibly contain information about other Orders, too.

And this is the missing link for me: How can I check the belongsToMany-relation in Invoice for date and order_id?

答:
There is a wherePivot method, which should do what you want.

From the docs:

Filtering Relationships Via Intermediate Table Columns:

You can also filter the results returned by belongsToMany using the
  wherePivot, wherePivotIn, and wherePivotNotIn methods when defining
  the relationship:

```<code>return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

return $this->belongsToMany('App\Role')->wherePivotNotIn('priority', [1, 2]);
</code>```

I have not tested it, but you should be able to do something like this:

```<code>public function isInvoiceable()
{
    // replace 'invoices()' with your relationship
    if ($this->invoices()->wherePivot('date', '>=', Carbon::now()->subMonth())->count() > 0) {
        return false;
    }

    return true;
}
</code>```

Body:
There is a wherePivot method, which should do what you want.

From the docs:

Filtering Relationships Via Intermediate Table Columns:

You can also filter the results returned by belongsToMany using the
  wherePivot, wherePivotIn, and wherePivotNotIn methods when defining
  the relationship:

return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

return $this->belongsToMany('App\Role')->wherePivotNotIn('priority', [1, 2]);

I have not tested it, but you should be able to do something like this:

public function isInvoiceable()
{
    // replace 'invoices()' with your relationship
    if ($this->invoices()->wherePivot('date', '>=', Carbon::now()->subMonth())->count() > 0) {
        return false;
    }

    return true;
}


问:
Passing data back to previous fragment from current fragment
I am Using Navigation Drawer in my app. I have one MainActivity and rest of are Fragments. So the issue is Suppose i have three fragments like A,B,C.

Now in A i have one button and i am sending data from A>B.

For example putSring("datafrom A","datafrom A");

Now in B i receive data From A.

I have one button in B,and i am sending data from B>C.

For example putSring("datafrom B","datafrom B");

Now in C i receive data From B.

Then, I have one Button in C,and sending data from C>B.

For example putSring("datafrom C","datafrom C");

So,seems like in B i am getting data from two different fragments. I tried with all using activity and it work well with startActivityforresult. but how can i manager when all are fragments.

答:
Things changed a lot since 2017. The answer I post is basically an example from https://developer.android.com and it presents a good solution where your fragments, in any number, do not know anything about each other and still you are able to create a simple and elegant mechanism that can be used without much struggle.

The answer is based on ViewModels and LiveData.

Note: If you are not familiar with Architecture Components I strongly advise you to learn about it as much as you can any time you can as it will increase your production speed and decrease the number of errors in your projects.

Everything below is a citation from the following link: source (Kotlin/Java)

Share data between fragments

It's very common that two or more fragments in an activity need to
  communicate with each other. Imagine a common case of master-detail
  fragments, where you have a fragment in which the user selects an item
  from a list and another fragment that displays the contents of the
  selected item. This case is never trivial as both fragments need to
  define some interface description, and the owner activity must bind
  the two together. In addition, both fragments must handle the scenario
  where the other fragment is not yet created or visible.

This common pain point can be addressed by using ViewModel objects.
  These fragments can share a ViewModel using their activity scope to
  handle this communication, as illustrated by the following sample
  code:

```<code>class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class MasterFragment : Fragment() {

    private lateinit var itemSelector: Selector

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
            // Update the UI
        }
    }
}

class DetailFragment : Fragment() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
            // Update the UI
        })
    }
}
</code>```

Notice that both fragments retrieve the activity that contains them.
  That way, when the fragments each get the ViewModelProvider, they
  receive the same SharedViewModel instance, which is scoped to this
  activity.

This approach offers the following benefits:

The activity does not need to do anything, or know anything about this
  communication.

Fragments don't need to know about each other besides
  the SharedViewModel contract. If one of the fragments disappears, the
  other one keeps working as usual.

Each fragment has its own lifecycle,
  and is not affected by the lifecycle of the other one. If one fragment
  replaces the other one, the UI continues to work without any problems.

Body:
Things changed a lot since 2017. The answer I post is basically an example from https://developer.android.com and it presents a good solution where your fragments, in any number, do not know anything about each other and still you are able to create a simple and elegant mechanism that can be used without much struggle.

The answer is based on ViewModels and LiveData.

Note: If you are not familiar with Architecture Components I strongly advise you to learn about it as much as you can any time you can as it will increase your production speed and decrease the number of errors in your projects.

Everything below is a citation from the following link: source (Kotlin/Java)

Share data between fragments

It's very common that two or more fragments in an activity need to
  communicate with each other. Imagine a common case of master-detail
  fragments, where you have a fragment in which the user selects an item
  from a list and another fragment that displays the contents of the
  selected item. This case is never trivial as both fragments need to
  define some interface description, and the owner activity must bind
  the two together. In addition, both fragments must handle the scenario
  where the other fragment is not yet created or visible.

This common pain point can be addressed by using ViewModel objects.
  These fragments can share a ViewModel using their activity scope to
  handle this communication, as illustrated by the following sample
  code:

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class MasterFragment : Fragment() {

    private lateinit var itemSelector: Selector

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
            // Update the UI
        }
    }
}

class DetailFragment : Fragment() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
            // Update the UI
        })
    }
}

Notice that both fragments retrieve the activity that contains them.
  That way, when the fragments each get the ViewModelProvider, they
  receive the same SharedViewModel instance, which is scoped to this
  activity.

This approach offers the following benefits:

The activity does not need to do anything, or know anything about this
  communication.

Fragments don't need to know about each other besides
  the SharedViewModel contract. If one of the fragments disappears, the
  other one keeps working as usual.

Each fragment has its own lifecycle,
  and is not affected by the lifecycle of the other one. If one fragment
  replaces the other one, the UI continues to work without any problems.


问:
Transforming a Dataframe in Pandas
I am struggling to find a way to transform excel data set to a tabular form using Pandas dataframe.

Source data set description:
Column 1 lists metrics names and column 2 onward, all columns have corresponding site wise and date wise metric values. All columns in the row number 1 from column 2 onward have a date to identify which day the data belongs to and row number 3 from column 2 onward to identify which site the data belongs to. Row 4 is where metric name (column 1) and metric values (column 2) start.

Desired output description:
Column 1 should list metric names
column 2 should list corresponding date of the data and site
column 3 should list corresponding site of data and date
column 4 should list corresponding metric value

Hope this makes sense. I could have uploaded a sample file but being new to stack overflow, guess need some points to do so.

So far i have tried transpose, melt etc with pandas dataframe but really not able to get the results.

Guess this could be a real challenger for data wrangling experts here.

答:
Hard to say without seeing the data but would you it help you to put each column in a list, manipulate the lists, then put them back in a DataFrame in a multi-dim list?</p>

```<code>col1 = df['column 1'].tolist()
col2 = df['column 2'].tolist()
col3 = df['column 3'].tolist()

for i in range(len(col1)):
    lst.append([col1[i],col2[i],col3[i]])

transposed_df = pd.DataFrame(lst, columns = ['metric names','date','site']
</code>```

Title: Transforming a Dataframe in Pandas

Body:
Hard to say without seeing the data but would you it help you to put each column in a list, manipulate the lists, then put them back in a DataFrame in a multi-dim list?

col1 = df['column 1'].tolist()
col2 = df['column 2'].tolist()
col3 = df['column 3'].tolist()

for i in range(len(col1)):
    lst.append([col1[i],col2[i],col3[i]])

transposed_df = pd.DataFrame(lst, columns = ['metric names','date','site']