问:
Bouncy castle with spring boot
I am trying to use Https over http, I generated the CA certificate with bouncy castle and generated from the .cer file the jks file, spring boot started successfully with the properties provided with an embedded tomcat.

The problem is that I'm getting always insecure ssl certificate from the browser (for example from chrome : This CA Root certificate is not trusted because it is not in the Trusted Root Certification Authorities store.) while I add the trust store programatically with another config class.

Here is my code:

```<code>import org.apache.commons.codec.binary.Base64; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.cmp.CertRepMessage; import org.bouncycastle.asn1.cmp.PKIBody; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.cert.CertException; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.cmp.CMPException; import org.bouncycastle.cert.cmp.ProtectedPKIMessage; import org.bouncycastle.cert.cmp.ProtectedPKIMessageBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;

import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.security.*; import java.security.cert.X509Certificate; import java.util.Date;

public class generateService {

    private static final String BC = BouncyCastleProvider.PROVIDER_NAME;

    private static X509CertificateHolder makeV3Certificate(KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
            throws GeneralSecurityException, IOException, OperatorCreationException, CertException
    {

        PublicKey subPub  = subKP.getPublic();
        PrivateKey issPriv = issKP.getPrivate();
        PublicKey  issPub  = issKP.getPublic();

        X509v3CertificateBuilder v1CertGen = new JcaX509v3CertificateBuilder(
                new X500Name(_issDN),
                BigInteger.valueOf(System.currentTimeMillis()),
                new Date(System.currentTimeMillis()),
                new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
                new X500Name(_subDN),
                subPub);

        ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(BC).build(issPriv);

        X509CertificateHolder certHolder = v1CertGen.build(signer);

        ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub);
        return certHolder;
    }

    public X509Certificate test(KeyPair kp) throws OperatorCreationException, GeneralSecurityException, CertException, IOException, CMPException {

    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    X509CertificateHolder cert = makeV3Certificate(kp, "CN=CA", kp, "CN=CA");
    GeneralName sender = new GeneralName(new X500Name("CN=CA"));
    GeneralName recipient = new GeneralName(new X500Name("CN=CA"));

    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(kp.getPrivate());
    ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient)
            .setBody(new PKIBody(PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence()))))
            .addCMPCertificate(cert)
            .build(signer);

    X509Certificate jcaCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(message.getCertificates()[0]);
    return jcaCert;
    }

    public void generateJKS() throws GeneralSecurityException, IOException, OperatorCreationException, CMPException, CertException {
        Provider bcProvider = new BouncyCastleProvider();
        Security.addProvider(bcProvider);
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        X509Certificate certificate = test(keyPair);

        final FileOutputStream os = new FileOutputStream("E:\\cert4.cer");
        os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));
        os.write(Base64.encodeBase64(certificate.getEncoded(), true));
        os.write("-----END CERTIFICATE-----\n".getBytes("US-ASCII"));
        os.close();

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null,null);
        X509Certificate[] certChain = new X509Certificate[1];
        certChain[0] = certificate;
        keyStore.setKeyEntry("myaliaskey", (Key)keyPair.getPrivate(), "secret".toCharArray(), certChain);
        OutputStream outputStream = new FileOutputStream("E:\\keystoreRSA4.jks");
        keyStore.store(outputStream, "secret".toCharArray());
        outputStream.flush();
        outputStream.close();

    }

    public static void main(String[] args) throws Exception {

        new generateService().generateJKS();
    } }
</code>```

Application.properties:

```<code>server.port = 8443 server.http.port = 8080 server.ssl.key-store =  E:\\keystoreRSA4.jks server.ssl.key-password = secret server.ssl.keyAlias = myaliaskey
</code>```

/***************************************************************************/

```<code>import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration public class SSLConfig {

    @PostConstruct
    private void configureSSL() {
        System.setProperty("https.protocols", "TLSv1.2");
        System.setProperty("javax.net.ssl.trustStore", "E:\\keystoreRSA4.jks");
        System.setProperty("javax.net.ssl.keyStore", "E:\\keystoreRSA4.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "secret");

    } }

import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;

@Configuration public class TomcatConfig {
    @Value("${server.http.port}")
    private int httpPort;

    @Value("${server.port}")
    private int httpsPort;

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }

    public Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("https");
        connector.setPort(httpPort);
        connector.setSecure(true);
        connector.setRedirectPort(httpsPort);
        return connector;
    } }
</code>```

Any help will be appreciated and thank you in advance.

答:
how i can figure it to let the browser accept it as trust certificate?

Fortunately, you can't. There's a discussion about the topic in this question:

If we simply said "HTTPS is now possible with self-signed certificates", your browser could not distinguish whether a site you are trying to visit has a self-signed cert because it is supposed to, or because you are being attacked. Thus, it would decrease security.

You have to add an exception to your browser to accept your certificate. Normally during development. For production use, you have to buy a certificate from a trusted vendor like Verisign.

To add an exception to your browser, please see this other question.

Cheers!

Title: Bouncy castle with spring boot

Body:
I am trying to use Https over http, I generated the CA certificate with bouncy castle and generated from the .cer file the jks file, spring boot started successfully with the properties provided with an embedded tomcat.

The problem is that I'm getting always insecure ssl certificate from the browser (for example from chrome : This CA Root certificate is not trusted because it is not in the Trusted Root Certification Authorities store.) while I add the trust store programatically with another config class.

Here is my code:

import org.apache.commons.codec.binary.Base64; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.cmp.CertRepMessage; import org.bouncycastle.asn1.cmp.PKIBody; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.cert.CertException; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.cmp.CMPException; import org.bouncycastle.cert.cmp.ProtectedPKIMessage; import org.bouncycastle.cert.cmp.ProtectedPKIMessageBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;

import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.security.*; import java.security.cert.X509Certificate; import java.util.Date;

public class generateService {

    private static final String BC = BouncyCastleProvider.PROVIDER_NAME;

    private static X509CertificateHolder makeV3Certificate(KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
            throws GeneralSecurityException, IOException, OperatorCreationException, CertException
    {

        PublicKey subPub  = subKP.getPublic();
        PrivateKey issPriv = issKP.getPrivate();
        PublicKey  issPub  = issKP.getPublic();

        X509v3CertificateBuilder v1CertGen = new JcaX509v3CertificateBuilder(
                new X500Name(_issDN),
                BigInteger.valueOf(System.currentTimeMillis()),
                new Date(System.currentTimeMillis()),
                new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
                new X500Name(_subDN),
                subPub);

        ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(BC).build(issPriv);

        X509CertificateHolder certHolder = v1CertGen.build(signer);

        ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub);
        return certHolder;
    }

    public X509Certificate test(KeyPair kp) throws OperatorCreationException, GeneralSecurityException, CertException, IOException, CMPException {

    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    X509CertificateHolder cert = makeV3Certificate(kp, "CN=CA", kp, "CN=CA");
    GeneralName sender = new GeneralName(new X500Name("CN=CA"));
    GeneralName recipient = new GeneralName(new X500Name("CN=CA"));

    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(kp.getPrivate());
    ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient)
            .setBody(new PKIBody(PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence()))))
            .addCMPCertificate(cert)
            .build(signer);

    X509Certificate jcaCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(message.getCertificates()[0]);
    return jcaCert;
    }

    public void generateJKS() throws GeneralSecurityException, IOException, OperatorCreationException, CMPException, CertException {
        Provider bcProvider = new BouncyCastleProvider();
        Security.addProvider(bcProvider);
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        X509Certificate certificate = test(keyPair);

        final FileOutputStream os = new FileOutputStream("E:\\cert4.cer");
        os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));
        os.write(Base64.encodeBase64(certificate.getEncoded(), true));
        os.write("-----END CERTIFICATE-----\n".getBytes("US-ASCII"));
        os.close();

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null,null);
        X509Certificate[] certChain = new X509Certificate[1];
        certChain[0] = certificate;
        keyStore.setKeyEntry("myaliaskey", (Key)keyPair.getPrivate(), "secret".toCharArray(), certChain);
        OutputStream outputStream = new FileOutputStream("E:\\keystoreRSA4.jks");
        keyStore.store(outputStream, "secret".toCharArray());
        outputStream.flush();
        outputStream.close();

    }

    public static void main(String[] args) throws Exception {

        new generateService().generateJKS();
    } }

Application.properties:

server.port = 8443 server.http.port = 8080 server.ssl.key-store =  E:\\keystoreRSA4.jks server.ssl.key-password = secret server.ssl.keyAlias = myaliaskey

/***************************************************************************/

import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration public class SSLConfig {

    @PostConstruct
    private void configureSSL() {
        System.setProperty("https.protocols", "TLSv1.2");
        System.setProperty("javax.net.ssl.trustStore", "E:\\keystoreRSA4.jks");
        System.setProperty("javax.net.ssl.keyStore", "E:\\keystoreRSA4.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "secret");

    } }

import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;

@Configuration public class TomcatConfig {
    @Value("${server.http.port}")
    private int httpPort;

    @Value("${server.port}")
    private int httpsPort;

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }

    public Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("https");
        connector.setPort(httpPort);
        connector.setSecure(true);
        connector.setRedirectPort(httpsPort);
        return connector;
    } }

Any help will be appreciated and thank you in advance.


来源: stackexchange

问:
Why Webix datatable cell values disappear after editing if template :function is used?
In one of my Webix datatable cells (editable), I am using a template:function to fetch and display the value. Now if I edit any of those cells, that edited value is not showing up instead the old value is showing.

If I again click on that cell, then I am able to see the newly typed value.
Why it is happening and how can I show the newly edited value in that cell.
It is happen only for cells under columns which is using template function.

In the below snippet please check that under parent column 'Place' , if I edit cells under 'climate' column the value is not showing up once mouse control is taken off. Same problem not happening for the cells under 'type' column.

Snippet: https://webix.com/snippet/8a63b3c7

What is the way to get rid of this problem?

Thanks.

答:
you are not using the template in right way, if you have to provide the constant value, there is no need to create the template. A template is used when we have to customize the data. Please follow the below link and please let me know in case you still face any issue, in template function first argument, provides the row data, please evaluate the field data from the row.

https://webix.com/snippet/310f5888

ContentLicense: CC BY-SA 3.0


问:
How to handle input in Flask with indexes inside name?
How to handle inputs form like these:

```<code><input type="text" name="time[1]" value="a">
<input type="text" name="time[2]" value="h">
<input type="text" name="time[3]" value="j">
</code>```

I tried to get values of inputs using the following approach:

```<code>for index, time in enumerate(request.form.getlist('time[]')):
   pass
</code>```

As a result I have to get value and index inside time[].

For example, when I send only a one field:

```<code><input type="text" name="time[3]" value="3">
</code>```

I should get value=j and index=3

How to do that?

答:
To Flask (or to any backend for that matter) those parameters are sent as individual form arguments called time[1], time[2] and time[3], not as some sort of a magical list. If you want to turn them into a list, or rather a dict as it's a sparse list, then you'll have to loop through your request.form and extract them. Something like:

```<code>form = request.form  # a short-hand for readability
time = {p[5:-1]: form[p] for p in form if p[:4] == "time" and p[4] == "[" and p[-1] == "]"}
</code>```

Then you can use the newly created time dictionary to loop through each of the parameters in an index:value manner:

```<code>for i, v in time.items():
    print("index={}, value={}".format(i, v))
</code>```

Or you can access your index directly to obtain the value, i.e. time['3']. Notice that we're using strings as indexes here, if sent 'indexes' are always integers, you can use int(p[5:-1]) when setting the key and then access the value with time[3].

If you want to use request.form.getlist() you'll need to name all your inputs the same (e.g. time[]) but then you won't have sparse lists.

Body:
How to handle inputs form like these:

<input type="text" name="time[1]" value="a">
<input type="text" name="time[2]" value="h">
<input type="text" name="time[3]" value="j">

I tried to get values of inputs using the following approach:

for index, time in enumerate(request.form.getlist('time[]')):
   pass

As a result I have to get value and index inside time[].

For example, when I send only a one field:

<input type="text" name="time[3]" value="3">

I should get value=j and index=3

How to do that?

Body:
To Flask (or to any backend for that matter) those parameters are sent as individual form arguments called time[1], time[2] and time[3], not as some sort of a magical list. If you want to turn them into a list, or rather a dict as it's a sparse list, then you'll have to loop through your request.form and extract them. Something like:

form = request.form  # a short-hand for readability
time = {p[5:-1]: form[p] for p in form if p[:4] == "time" and p[4] == "[" and p[-1] == "]"}

Then you can use the newly created time dictionary to loop through each of the parameters in an index:value manner:

for i, v in time.items():
    print("index={}, value={}".format(i, v))

Or you can access your index directly to obtain the value, i.e. time['3']. Notice that we're using strings as indexes here, if sent 'indexes' are always integers, you can use int(p[5:-1]) when setting the key and then access the value with time[3].

If you want to use request.form.getlist() you'll need to name all your inputs the same (e.g. time[]) but then you won't have sparse lists.


问:
Are immutable objects good practice?
Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety)
Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them?
Or is it not worth the inconvenience you have to create them?

答:
Another nice benefit of immutable structures is that you can locally cache instances of them and reuse them across multiple threads without fear of unexpected behaviors as would be the case if they were mutable.

For instance, suppose you are using an external caching service such as memcached or Velocity or some other equally simplistic distributed hashtable service. You could just use the C# client library and call it good enough. However, that is being wasteful with resources given a short-lived context like a web request scenario. What you really want is to pull each object from the cache once and only once in your context.

The safest way to get this job done is to place a local hashtable in your process in front of the cache provider. On the first request for the cache key you'd pull down the serialized byte stream that represents the object you wish to use and store that byte stream in your local hashtable. On subsequent requests for the same cache key, just look up the byte stream in the local hashtable and deserialize the object to a new instance for each request. This is to prevent multiple redundant trips to the cache server node for the same information that assumedly has not changed over the lifetime of your context.

With immutable structures, you could deserialize the byte stream only once on the first request and get away with storing the deserialized instance in the hashtable instead of the byte stream and just share that one single immutable instance of your object. This obviously cuts down on deserialization penalties which can add up rather quickly if your consuming code is written in such a fashion that it does not care how many calls it makes to the caching provider, assuming the cache is faster than querying your underlying data store.

Perhaps this is more of a subjective answer, but it's a specific problem that can be solved uniquely by using immutable structures so I thought it was relevant to share.

ContentLicense: CC BY-SA 2.5

Title: Are immutable objects good practice?


问:
Split collection into multiple collections
I want to create new list of list on basis of a single list.
I have a list like

```<code>public class OfficeLocator
{
    public String id{ get; set; }
    public string Geography{ get; set; }
    public string Country{ get; set; }
    public string State{ get; set; }
    public string OfficeName{ get; set; }
}
</code>```

I am trying to prepare an tree structured list

```<code>GeographyName="Asia",
{
   Country = "China",
   {
      State = "Hunan",
        {
            {
                OfficeId = "1",
                OfficeName = "Office 1"
            },
            {
                OfficeId = "2",
                OfficeName = "Office 2"
            }
        },
      State = "Hubei"
        {
            {
                OfficeId = "3",
                OfficeName = "Office 3"
            }
        }
    },
    Country = "India",
    {
      State = "Maharashtra",
        {
            {
                OfficeId = "4",
                OfficeName = "Office 4"
            },
            {
                OfficeId = "5",
                OfficeName = "Office 5"
            }
        },
      State = "Punjab"
        {
            {
                OfficeId = "6",
                OfficeName = "Office 6"
            }
        }
    },
},
GeographyName="Europe",
{
   Country = "UK",
   {
      State = "York",
        {
            {
                OfficeId = "7",
                OfficeName = "Office 7"
            },
            {
                OfficeId = "8",
                OfficeName = "Office 8"
            }
        }
    }
}
</code>```

I tried using some group by on Geography and Country.
But I am not getting the required output.

I can use looping logic to get the result, but I want to avoid it and try something with linq.

答:
Something like this?

```<code>var allRegionGroups = allOfficeLocators
    .GroupBy(ol => ol.Geography)
    .Select(gGroup => new
    {
        GeographyName = gGroup.Key,
        Countries = gGroup
            .GroupBy(ol => ol.Country)
            .Select(cGroup => new
            {
                Country = cGroup.Key,
                States = cGroup
                  .GroupBy(ol => ol.State)
                  .Select(sGroup => new
                  {
                      State = sGroup.Key,
                      OfficeList = sGroup
                       .Select(ol => new { OfficeId = ol.id, ol.OfficeName })
                       .ToList()
                  })
                 .ToList()
            })
            .ToList()
    })
    .ToList();
</code>```

How you can access all properties of the anonymous types:

```<code>foreach (var region in allRegionGroups)
{
    string geographyName = region.GeographyName;
    var allCountries = region.Countries;
    foreach (var c in allCountries)
    {
        string country = c.Country;
        var allStates = c.States;
        //  and so on...
    }
}
</code>```

Body:
I want to create new list of list on basis of a single list.
I have a list like

public class OfficeLocator
{
    public String id{ get; set; }
    public string Geography{ get; set; }
    public string Country{ get; set; }
    public string State{ get; set; }
    public string OfficeName{ get; set; }
}

I am trying to prepare an tree structured list

GeographyName="Asia",
{
   Country = "China",
   {
      State = "Hunan",
        {
            {
                OfficeId = "1",
                OfficeName = "Office 1"
            },
            {
                OfficeId = "2",
                OfficeName = "Office 2"
            }
        },
      State = "Hubei"
        {
            {
                OfficeId = "3",
                OfficeName = "Office 3"
            }
        }
    },
    Country = "India",
    {
      State = "Maharashtra",
        {
            {
                OfficeId = "4",
                OfficeName = "Office 4"
            },
            {
                OfficeId = "5",
                OfficeName = "Office 5"
            }
        },
      State = "Punjab"
        {
            {
                OfficeId = "6",
                OfficeName = "Office 6"
            }
        }
    },
},
GeographyName="Europe",
{
   Country = "UK",
   {
      State = "York",
        {
            {
                OfficeId = "7",
                OfficeName = "Office 7"
            },
            {
                OfficeId = "8",
                OfficeName = "Office 8"
            }
        }
    }
}

I tried using some group by on Geography and Country.
But I am not getting the required output.

I can use looping logic to get the result, but I want to avoid it and try something with linq.

Body:
Something like this?

var allRegionGroups = allOfficeLocators
    .GroupBy(ol => ol.Geography)
    .Select(gGroup => new
    {
        GeographyName = gGroup.Key,
        Countries = gGroup
            .GroupBy(ol => ol.Country)
            .Select(cGroup => new
            {
                Country = cGroup.Key,
                States = cGroup
                  .GroupBy(ol => ol.State)
                  .Select(sGroup => new
                  {
                      State = sGroup.Key,
                      OfficeList = sGroup
                       .Select(ol => new { OfficeId = ol.id, ol.OfficeName })
                       .ToList()
                  })
                 .ToList()
            })
            .ToList()
    })
    .ToList();

How you can access all properties of the anonymous types:

foreach (var region in allRegionGroups)
{
    string geographyName = region.GeographyName;
    var allCountries = region.Countries;
    foreach (var c in allCountries)
    {
        string country = c.Country;
        var allStates = c.States;
        //  and so on...
    }
}


问:
Global variable not updated inside function
I spent few hours trying to find the reason why the variable dataset_path which is a global variable is always undefined

```<code>var dataset_path ;

function myFunction() {
  offline_data_mainlooper_bitfinex();
  print_bilan();
}
function offline_data_mainlooper_bitfinex(){
    var hours_step_size = 1*2;
    var daily_step_size = 24*2,
    // dataset_path = './quote/bitfinex/from_1480550400to_1512100800_1hquote.json';
    // dataset_path =  ('./quote/bitfinex/from_1480550400to_1512100800quote.json') //thats's 30 min
    dataset_path =  './quote/bitfinex/from_1480550400to_1512100800_15mquote.json'
       //... somecode

}
function print_bilan(){
   var filename = './analysis/test_log.json';
   //... somecode
 console.log('Quote saved! to ' +dataset_path, filename)
}
</code>```

答:
It worked for me when I put a ; instead of a , after

```<code>var daily_step_size = 24*2,
</code>```

I think you are declaring a new var which scope is inside the function. So when you're calling the global one, it's undefined.

Hope it helps

Body:
I spent few hours trying to find the reason why the variable dataset_path which is a global variable is always undefined

var dataset_path ;

function myFunction() {
  offline_data_mainlooper_bitfinex();
  print_bilan();
}
function offline_data_mainlooper_bitfinex(){
    var hours_step_size = 1*2;
    var daily_step_size = 24*2,
    // dataset_path = './quote/bitfinex/from_1480550400to_1512100800_1hquote.json';
    // dataset_path =  ('./quote/bitfinex/from_1480550400to_1512100800quote.json') //thats's 30 min
    dataset_path =  './quote/bitfinex/from_1480550400to_1512100800_15mquote.json'
       //... somecode

}
function print_bilan(){
   var filename = './analysis/test_log.json';
   //... somecode
 console.log('Quote saved! to ' +dataset_path, filename)
}

Body:
It worked for me when I put a ; instead of a , after

var daily_step_size = 24*2,

I think you are declaring a new var which scope is inside the function. So when you're calling the global one, it's undefined.

Hope it helps


问:
Function declaration must have a name
I have strings of codes in my Main.Activity.kt of Android studio but I keep getting the error message "Function declaration must have a name: Unresolved reference"

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(2);
    displayPrice(2*5);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);
}
}
</code>```

答:
Replace (but this is not what you want) displayPrice(2*5); with display(2*5); (only to solve the unreferenced error, then you will see the price instead of the quantity). Also to display the price you need create the method :

private void displayPrice(int number) {
    \\ do price print.
}

The methoddisplayPrice is undeclared so that's why bad reference error appears.

Title: Function declaration must have a name

Body:
I have strings of codes in my Main.Activity.kt of Android studio but I keep getting the error message "Function declaration must have a name: Unresolved reference"

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(2);
    displayPrice(2*5);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);
}
}


问:
Maven: How to create a correct JDBC driver dependency, if I don't know which database the client will use?
I'm currently learning to use maven, I understood how to create a maven project using dependencies from maven repository - and now I have the following question:

If I have an application which uses a database access, for example via Hibernate, then I need to add a dependency representing the corresponding database driver, for example mysql-connector-java for MySql, ojdbc for Oracle and so on.

But what if I want the program to run on a different machine and I don't know what database engine it uses? What is the common way to solve this? Just import all possible drivers as dependencies? Or is there a more elegant way?

答:
Using a ORM (Object Relational Mapping) like Hibernate is the best solution since you write Java code that will be interpreted by Hibernate and translated into SQL queries.

At some point, you will have to decide which database are you going to use, then you will have to add the driver.

Another solution can be making configurations for different environments using maven: https://maven.apache.org/guides/mini/guide-building-for-different-environments.html


问:
Visual Studio XSD files with DLLs for Web Projects
I'm trying to create a DLL using a Dataset.XSD file to access my website's VistaDB database.  The DLL develops and builds fine but I need to build the DLL once and then change the "path" of the database in the all the Website projects that finally references the dll (different databases and therefor database paths for each website that references the dll in it's bin folder).

I can't get the ConfigurationManager.ConnectionString("myconstr").ConnectionString to stay in my DLL project.  As soon as I save it - it reverts back to whatever the Dataset.XSD file wants it to be (the database connectionstring that I developed it against).

答: I figured out that if I just open it up in notepad, make the changes, and then build it works like it should.  It's kind of a pain in the butt to do this every time I make a changes to the XSD file though but it's better than nothing, I guess.</p>

OwnerDisplayName: EdenMachine


问:
python and javascript with html generation
On a website that I manage, we have JSON files which contain page data. We then create the page using this JSON.

The data looks roughly like this (except a lot more complex).

```<code>[
  {"title": "Hello world", "content": "World, hello to you!"},
  {"title": "Hello world Part II", "content": "The sequel to hello world."},
  ...
]
</code>```

This data is then parsed into HTML. Now, here lies the issue: we need two versions of the HTML.

One needs to be static, outputted in the format of file-0.html which would be formatted with a title of Hello World and content of World, hello to you! and file-1.html (title=Hello World Part II, content=The sequel to hello world).

The second needs to be just a plain page file-all.html which includes a JavaScript that pulls the JSON via AJAX when its needed and creates a container for each page which includes subpages that have the content/titles for everything in the JSON.

Right now, we use Python to generate the HTML for the file-0.html static pages, and then JavaScript for the AJAX pages. While this works, it means there is a lot of code duplication for a pretty small project—every time we want to change the class of the
 title is wrapped in, we have to change two places with slightly different syntax.

Is there any good way of fixing this issue, so that all the code for generating page (or as much as possible) is in one language? (This would probably have to be JavaScript, since bandwidth is an issue—we'd like to avoid transferring HTML via AJAX if possible.)

答:
You can use the server to render the page and grab that with an AJAX response. While this avoids code duplication, it might be less efficient since you have to query the server to render each page, rather than making the client do it themselves (this might not be too much of an issue, though). It shouldn't take up too much bandwidth, since it's just HTML (unless you're throwing in templates from all sorts of places). This approach, of course, only works if you're using a dynamic web site.

Alternatively, you can implement all the rendering logic in JavaScript and use something like PyV8 to run it from within Python. I question the efficiency (and sanity) of this, though.

Body:
On a website that I manage, we have JSON files which contain page data. We then create the page using this JSON.

The data looks roughly like this (except a lot more complex).

[
  {"title": "Hello world", "content": "World, hello to you!"},
  {"title": "Hello world Part II", "content": "The sequel to hello world."},
  ...
]

This data is then parsed into HTML. Now, here lies the issue: we need two versions of the HTML.

One needs to be static, outputted in the format of file-0.html which would be formatted with a title of Hello World and content of World, hello to you! and file-1.html (title=Hello World Part II, content=The sequel to hello world).

The second needs to be just a plain page file-all.html which includes a JavaScript that pulls the JSON via AJAX when its needed and creates a container for each page which includes subpages that have the content/titles for everything in the JSON.

Right now, we use Python to generate the HTML for the file-0.html static pages, and then JavaScript for the AJAX pages. While this works, it means there is a lot of code duplication for a pretty small project—every time we want to change the class of the
 title is wrapped in, we have to change two places with slightly different syntax.

Is there any good way of fixing this issue, so that all the code for generating page (or as much as possible) is in one language? (This would probably have to be JavaScript, since bandwidth is an issue—we'd like to avoid transferring HTML via AJAX if possible.)


问:
JS statement gets executed in Safari, only in new tabs, but it shouldn't
I am having a really weird problem that I can't wrap my head around,the code below is supposed to make an XMLHTTPRequest if an alert window is closed in less than XY ms.

It works in all browsers and doesn't trigger the loadApi() function when I visit, just in Safari it gets executed no matter how long I wait until I close the alert.

But this only happens whenever I open a fresh tab in Safari and then visit the page, if I visit the same page again in the same tab the code doesn't get executed.

var a = window.performance.now();
    alert('yo yo yo');
var b = window.performance.now();

if ((b - a) < 80) {
    console.log('yes');
    loadApi(); // this makes the XMLHTTPRequest which triggers a DB insert
}
```

And it gets even weirder, in Safari, when I visit in a fresh tab the code gets executed and does the XMLHTTPRequest, but the console.log() never triggers. Console just shows up empty.

Is that a Safari bug, or am I doing something wrong?

Please help :)

答:
Ok I figured it out, the problem is that Safaris alert/prompt etc are not blocking the browser anymore for some time now.

So it seems that JS continues execution, sometimes, even after an alert is fired.

The solution was to start the counter, fire the alert, and then wrap the rest of the code in a setTimeout with a very short delay, I used 5ms.

That fixes it

Body:
I am having a really weird problem that I can't wrap my head around,the code below is supposed to make an XMLHTTPRequest if an alert window is closed in less than XY ms.

It works in all browsers and doesn't trigger the loadApi() function when I visit, just in Safari it gets executed no matter how long I wait until I close the alert.

But this only happens whenever I open a fresh tab in Safari and then visit the page, if I visit the same page again in the same tab the code doesn't get executed.

var a = window.performance.now();
    alert('yo yo yo');
var b = window.performance.now();

if ((b - a) < 80) {
    console.log('yes');
    loadApi(); // this makes the XMLHTTPRequest which triggers a DB insert
}

And it gets even weirder, in Safari, when I visit in a fresh tab the code gets executed and does the XMLHTTPRequest, but the console.log() never triggers. Console just shows up empty.

Is that a Safari bug, or am I doing something wrong?

Please help :)


问:
Restart exception handling if one part fails
I have the following snippet:

```<code>def check1(n):
    if len(n) != 4:
        return raw_input("Enter 4 digits only")
    else:
        return True

def check2(n):
    if n.isdigit() != True:
        return raw_input("Enter digits only")
    else:
        return True

def check3(n):
    if len(set(str(n))) != 4:
        return raw_input("Enter non duplicate numbers only")
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    if (check1(b) != True or check2(b) != True or check3(b) != True):
        if check1(b) != True:
            print check1(b)
        elif check2(b) != True:
            print check2(b)
        elif check3(b) != True:
            print check3(b)
    else:
        print b
</code>```

How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.

UPDATE
I've improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn't work properly. If I enter '1' consecutively, it bounces between different exceptions instead of staying on the first check.

```<code>def checks(n):
    if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
        return False
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    while checks(b) != True:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        if b.isdigit() != True:
            b = raw_input("Enter digits only")
        if len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")

    print b
</code>```

答:
What do you mean by "starts from the first one again?"  Do you mean go back to the raw_input? You could put it in a while and loop until you have a valid input.

I would also suggest combining your check functions into one.  You also call each one twice, when you really don't need to; just capture the response as you go.

```<code>valid_response = False
while not valid_response:
    input = raw_input("Enter your guess: ")
    valid_response = checkInput(input)
    if not valid_response:
        print valid_response
    else:
        print input
</code>```

Even that can be cleaned up further, but hopefully it will point you in the right direction.  I feel icky using valid_response to handle a string or a boolean there; you can probably find a way to separate the two by rethinking how your check function works.

Update

You've got a couple problems: You're still performing your checks multiple times, and you're combining your verification logic with your raw_input() calls.  Because you're checking both for validity of input (a boolean value) and a reason for invalid data (more options), it probably makes more sense to not use an external function.  Especially since we're only talking about a couple lines of code.  Try this:

```<code>sturn = 1
lturn = 8

# you never do anything with this variable "a". Did you mean to type "b" here?
a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in xrange(sturn, lturn):
    valid_input = False
    b = raw_input("Enter your guess: ")
    while not valid_input:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        elif b.isdigit() != True:
            b = raw_input("Enter digits only")
        elif len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")
        else:
            valid_input = True                 # breaks you out of your while loop
            print b
</code>```

The one thing I haven't really evaluated in this code is whether or not the three checks work, since I'm not quite sure what you're going for with them.  If you haven't already, it might be worth testing each one individually to make sure they are actually validating the user input the way you need them to.

Body:
I have the following snippet:

def check1(n):
    if len(n) != 4:
        return raw_input("Enter 4 digits only")
    else:
        return True

def check2(n):
    if n.isdigit() != True:
        return raw_input("Enter digits only")
    else:
        return True

def check3(n):
    if len(set(str(n))) != 4:
        return raw_input("Enter non duplicate numbers only")
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    if (check1(b) != True or check2(b) != True or check3(b) != True):
        if check1(b) != True:
            print check1(b)
        elif check2(b) != True:
            print check2(b)
        elif check3(b) != True:
            print check3(b)
    else:
        print b

How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.

UPDATE
I've improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn't work properly. If I enter '1' consecutively, it bounces between different exceptions instead of staying on the first check.

def checks(n):
    if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
        return False
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    while checks(b) != True:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        if b.isdigit() != True:
            b = raw_input("Enter digits only")
        if len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")

    print b

Body:
What do you mean by "starts from the first one again?"  Do you mean go back to the raw_input? You could put it in a while and loop until you have a valid input.

I would also suggest combining your check functions into one.  You also call each one twice, when you really don't need to; just capture the response as you go.

valid_response = False
while not valid_response:
    input = raw_input("Enter your guess: ")
    valid_response = checkInput(input)
    if not valid_response:
        print valid_response
    else:
        print input

Even that can be cleaned up further, but hopefully it will point you in the right direction.  I feel icky using valid_response to handle a string or a boolean there; you can probably find a way to separate the two by rethinking how your check function works.

Update

You've got a couple problems: You're still performing your checks multiple times, and you're combining your verification logic with your raw_input() calls.  Because you're checking both for validity of input (a boolean value) and a reason for invalid data (more options), it probably makes more sense to not use an external function.  Especially since we're only talking about a couple lines of code.  Try this:

sturn = 1
lturn = 8

# you never do anything with this variable "a". Did you mean to type "b" here?
a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in xrange(sturn, lturn):
    valid_input = False
    b = raw_input("Enter your guess: ")
    while not valid_input:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        elif b.isdigit() != True:
            b = raw_input("Enter digits only")
        elif len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")
        else:
            valid_input = True                 # breaks you out of your while loop
            print b

The one thing I haven't really evaluated in this code is whether or not the three checks work, since I'm not quite sure what you're going for with them.  If you haven't already, it might be worth testing each one individually to make sure they are actually validating the user input the way you need them to.


问:
How to have Monit send an alert when a file does not exist, but not when it does exist?
I have the following Monit check:

```<code>check file foo with path /run/foo
    if does not exist then alert
</code>```

This sends an alert when /run/foo does not exist. But when I login to the server and create /run/foo, I don't want Monit to send another alert now that the file does exist. How do I achieve that?

答:
Currently, there no way to prevent Monit from alerting on a subset of an event. You can set event filter or service filter but you cannot filter at failure or success level.

Documentation : https://mmonit.com/monit/documentation/monit.html#Disabling-alerts-for-some-service

Body:
I have the following Monit check:

check file foo with path /run/foo
    if does not exist then alert

This sends an alert when /run/foo does not exist. But when I login to the server and create /run/foo, I don't want Monit to send another alert now that the file does exist. How do I achieve that?


问:
AWS Data Pipeline Escaping Comma in emr activity step section
I am creating an aws datapipline using the architect provided in the aws web console.

Everything is setup ok, my emrcluster is configured and successfully started.

But when I am trying to submit a emr activity I come across following problem:

In the step section of the emr activity my requirement is to provide --packages argument with 3 packages

But as far as I understand steps in emractivity is a comma separated value and commas (,) are replaced with spaces in the resultant step argument.

On the other hand --packages argument is also a comma separated value in case of multiple packages.

Now when I am trying to pass this as argument commas get replaced with spaces that make the step invalid.

This is the statement I required as it is in the resultant emr step:

```<code>--packages com.amazonaws:aws-java-sdk-s3:1.11.228,org.apache.hadoop:hadoop-aws:2.6.0,org.postgresql:postgresql:42.1.4
</code>```

Any solution to escape the comma?

So far i try the \\\\ way as mentioned in http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-emractivity.html

Not worked.

答:
when u will be using \\\\, it will escape the slashes and comma will get replaced.
You can try using Three slashes, same has worked for me . Like  \\\, .
I hope that works

ContentLicense: CC BY-SA 4.0

Body:
I am creating an aws datapipline using the architect provided in the aws web console.

Everything is setup ok, my emrcluster is configured and successfully started.

But when I am trying to submit a emr activity I come across following problem:

In the step section of the emr activity my requirement is to provide --packages argument with 3 packages

But as far as I understand steps in emractivity is a comma separated value and commas (,) are replaced with spaces in the resultant step argument.

On the other hand --packages argument is also a comma separated value in case of multiple packages.

Now when I am trying to pass this as argument commas get replaced with spaces that make the step invalid.

This is the statement I required as it is in the resultant emr step:

--packages com.amazonaws:aws-java-sdk-s3:1.11.228,org.apache.hadoop:hadoop-aws:2.6.0,org.postgresql:postgresql:42.1.4

Any solution to escape the comma?

So far i try the \\\\ way as mentioned in http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-emractivity.html

Not worked.


问:
Prevent multiple service access same document in MongoDB till processing is done
I have multiple instances of a services. This service access a collection of unprocessed document. We are using MongoDB. The role of service is :

Fetch the first unprocessed document from collection A.

Make a Rest call using uuid.

Get the response and store the response in another collection B.

Multiple service may access the same document leading to duplicate. The steps which I can think to deal with this situation:

FindandModify() along with progress field. So we will call this function with query of progress field to be "0". We will update the value to 1 so other services can not access it. On getting the success from Rest call we can delete the record. On getting the failure we will again call the FindandModify() with update value to be "0" so other service can access  at later time.

We we call Find() function which will give us one document. We get the "_id" of the document and store it into another collection. If another service also gets the same document and that document "_id" is already present. Then it will not be insert again and that service again call Find() function.

What would be the performance and bottleneck of these approaches. Also do we have any other better approach which will enhance the performance.

答:
FindandModify() along with progress field. So we will call this function with query of progress field to be "0". We will update the value to 1 so other services can not access it. On getting the success from Rest call we can delete the record. On getting the failure we will again call the FindandModify() with update value to be "0" so other service can access at later time.

This solution is OK and is simpler and faster than the second.

We we call Find() function which will give us one document. We get the "_id" of the document and store it into another collection. If another service also gets the same document and that document "_id" is already present. Then it will not be insert again and that service again call Find() function.

This solution (as you presented) would not work unless the document is removed from the first collection after it is inserted in the second, otherwise the processes will be caught in an infinite loop. The drawback is that this solution implies two collections and the document moving process.

In any case, you must take into account the failure of the processes in any of the phases and you must be able to detect failure and recover from it.


问:
Can i use Eureka Client and Ribbon with spring 3.1 to access other microservice registered using Eureka?
I am having spring 3.1 based web application and i want to write new module as a microservice with spring-boot. I am new to this microservice world, so I have few doubts regarding communication between these two services.

I am thinking to use eureka client with my existing application to access other microservice. I am not sure whether eureka client support spring 3.1 and ribbon client.

Any pointer will be helpful....

答: I wrote a library for my current company, that makes it possible to communicate from a spring 3.1.x based application with eureka and other microservices using the resttemplate (with ribbon etc. - just like the loadbalanced resttemplate in spring boot applications). We are in progress of releasing that as open source, you may find it soon here: https://github.com/dm-drogeriemarkt (as spring3-eureka-ribbon something)</p>


问:
Need Help with Simple JavaScript
I need help with javascript. I need to create a hidden input with the name "keywords", and write a JS function that populates it with the values of the checked checkboxes when the form is submitted.

First, I had to change the "," to a "|" because that is the correct syntax for ExpressionEngine. But for some reason the search will not work if there is a "|" at the end.

So for example if I select three checkboxes the output to the hidden keyword box is Aberdeen|Harrisburg|Avon| and this will not work with the search, but if I manually enter Aberdeen|Harrisburg|Avon with no "|" at the end, the search will work.

So How can I change this line to not have a "|" at the end of the keywords
templateValues += checkBox.value + "|";

答:
Try this:</p>

```<code><form action="sdmlsurvey.com/search/eresults"  method="post" onsubmit="populateTemplateValues()">
            <script type="text/javascript">
                function populateTemplateValues()
                {
                    var checkBoxes = document.getElementsByName("template");
                    var len = checkBoxes.length;
                    var templateValues = "";
                    for(var i=0; i<len; i++)
                    {
                        var checkBox = checkBoxes[i];
                        if(checkBox.checked)
                        templateValues += checkBox.value + "|";
                    }
                    document.getElementsByName("keywords")[0].value = templateValues.replace(/\|$/g, "");
                    alert(document.getElementsByName("keywords")[0].value );// Remove this in actual script. This is just for demo.
                    return true;
                }
            </script>
            <input type="hidden" name="keywords" value=""/>
            <input type="checkbox" name="template" value="1"/> 1<br/>
            <input type="checkbox" name="template" value="2"/> 2<br/>
            <input type="checkbox"  name="template" value="3"/> 3<br/>
            <input type="submit" value="Submit"/>
        </form>
</code>```

Title: Need Help with Simple JavaScript

Body:
Try this:

<form action="sdmlsurvey.com/search/eresults"  method="post" onsubmit="populateTemplateValues()">
            <script type="text/javascript">
                function populateTemplateValues()
                {
                    var checkBoxes = document.getElementsByName("template");
                    var len = checkBoxes.length;
                    var templateValues = "";
                    for(var i=0; i<len; i++)
                    {
                        var checkBox = checkBoxes[i];
                        if(checkBox.checked)
                        templateValues += checkBox.value + "|";
                    }
                    document.getElementsByName("keywords")[0].value = templateValues.replace(/\|$/g, "");
                    alert(document.getElementsByName("keywords")[0].value );// Remove this in actual script. This is just for demo.
                    return true;
                }
            </script>
            <input type="hidden" name="keywords" value=""/>
            <input type="checkbox" name="template" value="1"/> 1<br/>
            <input type="checkbox" name="template" value="2"/> 2<br/>
            <input type="checkbox"  name="template" value="3"/> 3<br/>
            <input type="submit" value="Submit"/>
        </form>


问:
How to hide or change the selection decorator on html buttons using bootstrap or css?
I am using arrows buttons like these ones:

```<code><button type="button" class="btn btn-default btn-arrow-left" > </button>
</code>```

```<code>body { /* just for this demo. */
    padding: 30px;
}
.btn { /* just for this demo. */
    margin-top: 5px;
}
.btn-arrow-right,
.btn-arrow-left {
    position: relative;
    padding-left: 18px;
    padding-right: 18px;
}
.btn-arrow-right {
    padding-left: 36px;
}
.btn-arrow-left {
    padding-right: 36px;
}
.btn-arrow-right:before,
.btn-arrow-right:after,
.btn-arrow-left:before,
.btn-arrow-left:after { /* make two squares (before and after), looking similar to the button */
    content:"";
    position: absolute;
    top: 5px; /* move it down because of rounded corners */
    width: 22px; /* same as height */
    height: 22px; /* button_outer_height / sqrt(2) */
    background: inherit; /* use parent background */
    border: inherit; /* use parent border */
    border-left-color: transparent; /* hide left border */
    border-bottom-color: transparent; /* hide bottom border */
    border-radius: 0px 4px 0px 0px; /* round arrow corner, the shorthand property doesn't accept "inherit" so it is set to 4px */
    -webkit-border-radius: 0px 4px 0px 0px;
    -moz-border-radius: 0px 4px 0px 0px;
}
.btn-arrow-right:before,
.btn-arrow-right:after {
    transform: rotate(45deg); /* rotate right arrow squares 45 deg to point right */
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}
.btn-arrow-left:before,
.btn-arrow-left:after {
    transform: rotate(225deg); /* rotate left arrow squares 225 deg to point left */
    -webkit-transform: rotate(225deg);
    -moz-transform: rotate(225deg);
    -o-transform: rotate(225deg);
    -ms-transform: rotate(225deg);
}
.btn-arrow-right:before,
.btn-arrow-left:before { /* align the "before" square to the left */
    left: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:after { /* align the "after" square to the right */
    right: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:before { /* bring arrow pointers to front */
    z-index: 1;
}
.btn-arrow-right:before,
.btn-a
</code>```

But I do not know how can I hide or change the yellow decorator when it is selected. Is it possible?

NOTE: I am working with Bootstrap v3.3.7

答:
The yellow line is the outline which appears on focus of the buttons. You can get rid of it by using below CSS code.</p>

```<code>.btn {
    outline: 0 !important;
}
</code>```

Body:
I am using arrows buttons like these ones:

<button type="button" class="btn btn-default btn-arrow-left" > </button>

body { /* just for this demo. */
    padding: 30px;
}
.btn { /* just for this demo. */
    margin-top: 5px;
}
.btn-arrow-right,
.btn-arrow-left {
    position: relative;
    padding-left: 18px;
    padding-right: 18px;
}
.btn-arrow-right {
    padding-left: 36px;
}
.btn-arrow-left {
    padding-right: 36px;
}
.btn-arrow-right:before,
.btn-arrow-right:after,
.btn-arrow-left:before,
.btn-arrow-left:after { /* make two squares (before and after), looking similar to the button */
    content:"";
    position: absolute;
    top: 5px; /* move it down because of rounded corners */
    width: 22px; /* same as height */
    height: 22px; /* button_outer_height / sqrt(2) */
    background: inherit; /* use parent background */
    border: inherit; /* use parent border */
    border-left-color: transparent; /* hide left border */
    border-bottom-color: transparent; /* hide bottom border */
    border-radius: 0px 4px 0px 0px; /* round arrow corner, the shorthand property doesn't accept "inherit" so it is set to 4px */
    -webkit-border-radius: 0px 4px 0px 0px;
    -moz-border-radius: 0px 4px 0px 0px;
}
.btn-arrow-right:before,
.btn-arrow-right:after {
    transform: rotate(45deg); /* rotate right arrow squares 45 deg to point right */
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}
.btn-arrow-left:before,
.btn-arrow-left:after {
    transform: rotate(225deg); /* rotate left arrow squares 225 deg to point left */
    -webkit-transform: rotate(225deg);
    -moz-transform: rotate(225deg);
    -o-transform: rotate(225deg);
    -ms-transform: rotate(225deg);
}
.btn-arrow-right:before,
.btn-arrow-left:before { /* align the "before" square to the left */
    left: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:after { /* align the "after" square to the right */
    right: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:before { /* bring arrow pointers to front */
    z-index: 1;
}
.btn-arrow-right:before,
.btn-a

But I do not know how can I hide or change the yellow decorator when it is selected. Is it possible?

NOTE: I am working with Bootstrap v3.3.7

Body:
The yellow line is the outline which appears on focus of the buttons. You can get rid of it by using below CSS code.

.btn {
    outline: 0 !important;
}


问:
Retrieve the List property count of realm for tableview Swift
I am using Realm 3 and Swift 4 and still new to Realm and Swift. Need a guidance here :)

Given this realm model

```<code>class Person: Object, Mappable {
    let dog = List<Dog>()

    required convenience init?(map: Map) {
        self.init()
    }
}
</code>```

How can I get the dog count of each person?

What i want to achieve is there are multiple sections on my table view and for each person there will be dog list for the respective person.

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let owner = realm.objects(Person.self)
    return owner.dog.count // This is not working. What should I change it to ?
}
</code>```

I have been searching through the web but couldn't find any guide on such problem.

Any help given is highly appreciated. Thanks!

答:
Have you tried query logic.

```<code>realm.objects(Person).filter("dogs.@count > 0")
</code>```

or

```<code>realm.objects(Person).filter("ANY dogs.@count > 0")
</code>```

Body:
I am using Realm 3 and Swift 4 and still new to Realm and Swift. Need a guidance here :)

Given this realm model

class Person: Object, Mappable {
    let dog = List<Dog>()

    required convenience init?(map: Map) {
        self.init()
    }
}

How can I get the dog count of each person?

What i want to achieve is there are multiple sections on my table view and for each person there will be dog list for the respective person.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let owner = realm.objects(Person.self)
    return owner.dog.count // This is not working. What should I change it to ?
}

I have been searching through the web but couldn't find any guide on such problem.

Any help given is highly appreciated. Thanks!

Body:
Have you tried query logic.

realm.objects(Person).filter("dogs.@count > 0")

or

realm.objects(Person).filter("ANY dogs.@count > 0")


问:
Writing to a memory mapped text file printing NULL till the end of mapped memory
In this code, Im writing some text to a memory mapped text file. Data is written to the file successfully, but when i open it with notepad, after the written data, "NULL" is repeatedly written upto the mapped memory limit which is greater than the text i have written.

What could be the possible reason?

```<code>pLogMsg = (char*)calloc(1024,sizeof(char));
printf("[INFO] entering logger writeback thread\n");

log_file = CreateFile (TEXT("one.txt"),             // Open one.txt.
                    GENERIC_READ | GENERIC_WRITE,   // Open for reading and writing
                    FILE_SHARE_WRITE,               // file share
                    NULL,                           // No security
                    OPEN_ALWAYS,                    // Open or create
                    FILE_ATTRIBUTE_NORMAL,          // Normal file
                    NULL);                          // No template file
if (log_file == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant open file GLE %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
hMapping = CreateFileMapping( log_file, 0, PAGE_READWRITE, 0,4096 ,0 );
if (hMapping == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant create file mapping %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pFileData = (CHAR*)MapViewOfFile( hMapping, FILE_MAP_ALL_ACCESS, 0,0, 0 );
if (pFileData == NULL)
{
    printf("%d [ERR] cant mapview of file %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pLogMsg = LogPrint();//returns a null terminated string
memcpy(pFileData,pLogMsg,strlen(pLogMsg));
pFileData += strlen(pLogMsg);
free(pLogMsg);
</code>```

答:
first of all CreateFileMapping and MapViewOfFile this is bad solution for log file. you need create/open file with FILE_APPEND_DATA access instead GENERIC_READ | GENERIC_WRITE - so call must look like:

```<code>HANDLE log_file = CreateFileW(L"one.txt",
    FILE_APPEND_DATA,
    FILE_SHARE_WRITE|FILE_SHARE_READ,
    NULL,
    OPEN_ALWAYS,
    FILE_ATTRIBUTE_NORMAL,
    NULL);
</code>```

in this case you open file with FILE_APPEND_DATA and SYNCHRONIZE (because no FILE_FLAG_OVERLAPPED):

If the caller sets only the FILE_APPEND_DATA and SYNCHRONIZE flags, it
  can write only to the end of the file, and any offset information
  about write operations to the file is ignored. The file will
  automatically be extended as necessary for this type of operation.

after this you need log via WriteFile - it will be automatically append to the end of file. this is what exactly need for log file.

however, if want use CreateFileMapping and MapViewOfFile - at first  CreateFileMapping return 0 on error, so check
if (hMapping == INVALID_HANDLE_VALUE) is wrong

if you want change file size - you need use for this SetFileInformationByHandle with FileEndOfFileInfo (vista+)or NtSetInformationFile with FileEndOfFileInformation (working everywhere, how not hard understand SetFileInformationByHandle is only very thin shell over NtSetInformationFile or ZwSetInformationFile (in user mode this is the same function)). use SetFilePointer followed by SetEndOfFile also possible but bad and not effective choice - you will be have 2 calls in src code instead on single. in binary - you will even more worse situation: first you set file position, that SetEndOfFile read this file position and finally call NtSetInformationFile with this position. so 3 calls instead one. and assume that nobody change file position (on this handle) between SetFilePointer and SetEndOfFile calls

but need clear understand that call SetFileInformationByHandle with FileEndOfFileInfo you can only after you unmap view and close section. otherwise you got error ERROR_USER_MAPPED_FILE (STATUS_USER_MAPPED_FILE )

If CreateFileMapping is called to create a file mapping object for
  hFile, UnmapViewOfFile must be called first to unmap all views and
  call CloseHandle to close the file mapping object before you can
  call SetEndOfFile.

Body:
In this code, Im writing some text to a memory mapped text file. Data is written to the file successfully, but when i open it with notepad, after the written data, "NULL" is repeatedly written upto the mapped memory limit which is greater than the text i have written.

What could be the possible reason?

pLogMsg = (char*)calloc(1024,sizeof(char));
printf("[INFO] entering logger writeback thread\n");

log_file = CreateFile (TEXT("one.txt"),             // Open one.txt.
                    GENERIC_READ | GENERIC_WRITE,   // Open for reading and writing
                    FILE_SHARE_WRITE,               // file share
                    NULL,                           // No security
                    OPEN_ALWAYS,                    // Open or create
                    FILE_ATTRIBUTE_NORMAL,          // Normal file
                    NULL);                          // No template file
if (log_file == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant open file GLE %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
hMapping = CreateFileMapping( log_file, 0, PAGE_READWRITE, 0,4096 ,0 );
if (hMapping == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant create file mapping %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pFileData = (CHAR*)MapViewOfFile( hMapping, FILE_MAP_ALL_ACCESS, 0,0, 0 );
if (pFileData == NULL)
{
    printf("%d [ERR] cant mapview of file %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pLogMsg = LogPrint();//returns a null terminated string
memcpy(pFileData,pLogMsg,strlen(pLogMsg));
pFileData += strlen(pLogMsg);
free(pLogMsg);

Body:
first of all CreateFileMapping and MapViewOfFile this is bad solution for log file. you need create/open file with FILE_APPEND_DATA access instead GENERIC_READ | GENERIC_WRITE - so call must look like:

HANDLE log_file = CreateFileW(L"one.txt",
    FILE_APPEND_DATA,
    FILE_SHARE_WRITE|FILE_SHARE_READ,
    NULL,
    OPEN_ALWAYS,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

in this case you open file with FILE_APPEND_DATA and SYNCHRONIZE (because no FILE_FLAG_OVERLAPPED):

If the caller sets only the FILE_APPEND_DATA and SYNCHRONIZE flags, it
  can write only to the end of the file, and any offset information
  about write operations to the file is ignored. The file will
  automatically be extended as necessary for this type of operation.

after this you need log via WriteFile - it will be automatically append to the end of file. this is what exactly need for log file.

however, if want use CreateFileMapping and MapViewOfFile - at first  CreateFileMapping return 0 on error, so check
if (hMapping == INVALID_HANDLE_VALUE) is wrong

if you want change file size - you need use for this SetFileInformationByHandle with FileEndOfFileInfo (vista+)or NtSetInformationFile with FileEndOfFileInformation (working everywhere, how not hard understand SetFileInformationByHandle is only very thin shell over NtSetInformationFile or ZwSetInformationFile (in user mode this is the same function)). use SetFilePointer followed by SetEndOfFile also possible but bad and not effective choice - you will be have 2 calls in src code instead on single. in binary - you will even more worse situation: first you set file position, that SetEndOfFile read this file position and finally call NtSetInformationFile with this position. so 3 calls instead one. and assume that nobody change file position (on this handle) between SetFilePointer and SetEndOfFile calls

but need clear understand that call SetFileInformationByHandle with FileEndOfFileInfo you can only after you unmap view and close section. otherwise you got error ERROR_USER_MAPPED_FILE (STATUS_USER_MAPPED_FILE )

If CreateFileMapping is called to create a file mapping object for
  hFile, UnmapViewOfFile must be called first to unmap all views and
  call CloseHandle to close the file mapping object before you can
  call SetEndOfFile.


问:
Fragment content overlapping toolbar
Implementing a BottomNavigationView with viewpager and tablayout.Each navigation view is a fragment in first fragment ("NewsFeedFragment") i want to use tablayout attached with a viewpager. Result come correct but the content of the fragment overlaps the parent toolbar.

Here is how i am trying to use it.

Home.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.M1Activity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="6dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />
</code>```

NewsFragment.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.HomeActivity">

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorAccent"
    app:tabTextColor="#FFF" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Here is result i get.

And what i basically trying exactly to implement is.

答:
Add the tab layout inside AppBarLayout as shown below</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.tablayoutappbar.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            app:tabGravity="fill"
            app:tabMode="fixed"
            android:layout_height="wrap_content"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text"/>

    </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Fragment content overlapping toolbar

Body:
Implementing a BottomNavigationView with viewpager and tablayout.Each navigation view is a fragment in first fragment ("NewsFeedFragment") i want to use tablayout attached with a viewpager. Result come correct but the content of the fragment overlaps the parent toolbar.

Here is how i am trying to use it.

Home.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.M1Activity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="6dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />

NewsFragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.HomeActivity">

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorAccent"
    app:tabTextColor="#FFF" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Here is result i get.

And what i basically trying exactly to implement is.

Body:
Add the tab layout inside AppBarLayout as shown below

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.tablayoutappbar.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            app:tabGravity="fill"
            app:tabMode="fixed"
            android:layout_height="wrap_content"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text"/>

    </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>