问:
No bean named 'groovyPagesTemplateEngine' is defined when upgrading grails from 1.3.7 to 2.4.4
We are upgrading grails version from 1.3.7 to 2.4.4 and see the below exception in the logs. Does anyone know what I am missing? Any help is greatly appreciated.

I have updated all the dependencies below to 2.4.4 along with grails-web:

grails-bootstrap

grails-core

grails-resources

grails-spring

grails-web

grails-project-api

grails-maven-plugin

```<code>2017-07-04 11:08:24,787 INFO  [io.undertow.servlet] (default task-1) Initializing Spring FrameworkServlet 'gsp'
2017-07-04 11:08:24,790 INFO  [org.codehaus.groovy.grails.web.pages.GroovyPagesServlet] (default task-1) FrameworkServlet 'gsp': initialization started
2017-07-04 11:08:24,791 INFO  [io.undertow.servlet] (default task-1) GSP servlet initialized
2017-07-04 11:08:24,833 ERROR [org.codehaus.groovy.grails.web.pages.GroovyPagesServlet] (default task-1) Context initialization failed: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'groovyPagesTemplateEngine' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:570)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1114)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:279)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:270)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
    at org.codehaus.groovy.grails.web.pages.GroovyPagesServlet.initFrameworkServlet(GroovyPagesServlet.java:114)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:460)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
    at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
    at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:239)
    at io.undertow.servlet.core.ManagedServlet.getServlet(ManagedServlet.java:171)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:84)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:285)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:264)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:175)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:792)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
In case if anyone needs help on this - With grails 2.4.4, the groovyPagesTemplateEngine is moved to a different jar by name grails-web-gsp-2.4.4.jar

Including this along with grails-web-gsp-taglib-2.4.4.jar resolved the issue.

Body:
We are upgrading grails version from 1.3.7 to 2.4.4 and see the below exception in the logs. Does anyone know what I am missing? Any help is greatly appreciated.

I have updated all the dependencies below to 2.4.4 along with grails-web:

grails-bootstrap

grails-core

grails-resources

grails-spring

grails-web

grails-project-api

grails-maven-plugin

2017-07-04 11:08:24,787 INFO  [io.undertow.servlet] (default task-1) Initializing Spring FrameworkServlet 'gsp'
2017-07-04 11:08:24,790 INFO  [org.codehaus.groovy.grails.web.pages.GroovyPagesServlet] (default task-1) FrameworkServlet 'gsp': initialization started
2017-07-04 11:08:24,791 INFO  [io.undertow.servlet] (default task-1) GSP servlet initialized
2017-07-04 11:08:24,833 ERROR [org.codehaus.groovy.grails.web.pages.GroovyPagesServlet] (default task-1) Context initialization failed: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'groovyPagesTemplateEngine' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:570)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1114)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:279)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:270)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
    at org.codehaus.groovy.grails.web.pages.GroovyPagesServlet.initFrameworkServlet(GroovyPagesServlet.java:114)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:460)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
    at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
    at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
    at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:239)
    at io.undertow.servlet.core.ManagedServlet.getServlet(ManagedServlet.java:171)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:84)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:285)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:264)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:175)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:792)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)


来源: stackexchange

问:
Remove duplicate attribute from HTMLString through regex
I am having a HtmlString where the some tag is having multiple "href" attribute. I have to remove one of them. If href attribute is more then 1 then have to remove blank href attribute through regex. </p>

```<code><p>
  Contrary to popular belief, Lorem Ipsum is not simply random text.It has
  <a title="Test PDF for RTF" href="" title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
     Test PDF
  </a>
  roots in a piece of classical Latin literature from 45 BC, making
  <a title="Learn More" href="test.html" title="Learn More" >
    Learn More
  </a>
  it over 2000 years old. Richard McClintock,
  <a title="Test Page" href="" >
    Test Page
  </a>
  Latin professor at Hampden-Sydney College in Virginia,
  <a title="Test PDF for RTF" href="" title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
    Test PDF
  </a>
  looked up one of the more obscure Latin words, consectetur
</p>
</code>```

答:
If it does not matter to leave  without a href when there is only one empty href:
/\s?href=\"\/?\"/ would match all the occurrences of empty hrefs

Yo have not specified in which language you will use the regular expression so it might require a little tweaking.

ContentLicense: CC BY-SA 3.0

Body:
I am having a HtmlString where the some tag is having multiple "href" attribute. I have to remove one of them. If href attribute is more then 1 then have to remove blank href attribute through regex.

  Contrary to popular belief, Lorem Ipsum is not simply random text.It has

     Test PDF

  roots in a piece of classical Latin literature from 45 BC, making

    Learn More

  it over 2000 years old. Richard McClintock,

    Test Page

  Latin professor at Hampden-Sydney College in Virginia,

    Test PDF

  looked up one of the more obscure Latin words, consectetur


问:
PHP - Convert this string to another date/time format
I'm working with an API that returns timestamps in this format:

```<code>07/23/2017 23:39:21
</code>```

The format is: MM/DD/YYYY HH:MM:SS

I need to covert this string so it displays in this format on my webpage:

23 July 2017, 11:39pm

Is this possible?

答:
Take a look at  http://php.net/manual/de/datetime.createfromformat.php. You'll get a DateTime object which you can convert in the format you desire.

Like so:

```<code><?php
$date = DateTime::createFromFormat('m/d/Y H:i:s', '07/23/2017 23:39:21');
echo $date->format('d M Y, h:ia');
?>
</code>```

Body:
I'm working with an API that returns timestamps in this format:

07/23/2017 23:39:21

The format is: MM/DD/YYYY HH:MM:SS

I need to covert this string so it displays in this format on my webpage:

23 July 2017, 11:39pm

Is this possible?

Body:
Take a look at  http://php.net/manual/de/datetime.createfromformat.php. You'll get a DateTime object which you can convert in the format you desire.

Like so:

<?php
$date = DateTime::createFromFormat('m/d/Y H:i:s', '07/23/2017 23:39:21');
echo $date->format('d M Y, h:ia');
?>


问:
What strategy to adopt to handle connection loss in WCF
We have a lot(~15) WCF services on the same server. To connect to them, we have a class(which I named ClientConnection). This class manage all the different service on the client side to one particular server.

This class is responsible of creating the Channel(and their bindings) for every service that is asked(and cache them).

Now, what if the connection broke(let's imagine that one switch was down, or one server is too busy to answer), I would like to have a fallback strategy.

It means to detect that it brokes, and then try to restore the connection.

Currently I've a "watchdog" in this class that verify that it can reach the remote service, if not it raise an event.

When I get this event, what should I do? Refresh the channel? Dispose it and create a new one? Also, since I've 10-15 active services to the same server, should I restore them anyway?

I think I should not be the first one to have this issue, but I struggle to find a good strategy on how to manage all thoses issues

答:
This sounds like a good fit for the Circuit Breaker Pattern

The long and short of it is that you essentially have something that tolerates failures with retry behaviour up to a point, and then has a back-off behaviour to gradually try to re-establish the connection.


问:
do I need multiple tables or single?
I developing a tool which may got more than a million data to fill in.

current i have designed single table with 36 coloumns. my question is do I need to divide these into multiple tables or single??

If single what is the advantage and disadvantage

if multiple then what is the advantage and disadvantage

and what will be the engine to use for speed...

my concern is a large database which will have atleast 50000 queries perday..

any help??

答:
You should model your database according to the data you want to store.  This is called "normalization": Essentially, each piece of information should only be stored once, otherwise a table cell should point to another row or table containing the value.  If, for example, you have table containing phone numbers, and one column contains the area code, you will likely have more than one phone number with the same value in the same column.  Once this happens, you should set up a new table for area codes and link to its entries by referencing the primary key of the row the desired area code is stored in.

So instead of

```<code>id | area code | number
---+-----------+---------
1  | 510       | 555-1234
2  | 510       | 555-1235
3  | 215       | 555-1236
4  | 215       | 555-1237
</code>```

you would have

```<code>id | area code    id | number   | area code
---+----------    ---+----------+-----------
1  | 510          1  | 555-1234 | 1
2  | 215          2  | 555-1235 | 1
                  3  | 555-1236 | 2
                  4  | 555-1237 | 2
</code>```

The more occurences of the same value you have, the more likely will you save memory and get quicker performance if you organize your data in this way, especially when you're handling string values or binary data.  Also, if an area code would change, all you need to do is update a single cell instead of having to perform an update operation on the whole table.

Try this tutorial.

ContentLicense: CC BY-SA 2.5

Title: do I need multiple tables or single?

Body:
You should model your database according to the data you want to store.  This is called "normalization": Essentially, each piece of information should only be stored once, otherwise a table cell should point to another row or table containing the value.  If, for example, you have table containing phone numbers, and one column contains the area code, you will likely have more than one phone number with the same value in the same column.  Once this happens, you should set up a new table for area codes and link to its entries by referencing the primary key of the row the desired area code is stored in.

So instead of

id | area code | number
---+-----------+---------
1  | 510       | 555-1234
2  | 510       | 555-1235
3  | 215       | 555-1236
4  | 215       | 555-1237

you would have

id | area code    id | number   | area code
---+----------    ---+----------+-----------
1  | 510          1  | 555-1234 | 1
2  | 215          2  | 555-1235 | 1
                  3  | 555-1236 | 2
                  4  | 555-1237 | 2

The more occurences of the same value you have, the more likely will you save memory and get quicker performance if you organize your data in this way, especially when you're handling string values or binary data.  Also, if an area code would change, all you need to do is update a single cell instead of having to perform an update operation on the whole table.

Try this tutorial.


问:
convert date to continuous variable in R
How can I convert date to continuous variable staring from 1. I tried as.numeric but R starts counting from default January 1, 1970 while my data start Oct 7, 2009.

I need to do this conversion to plot the date on two x-axes (1 and 3).

```<code>plot(LAI~Date, data=LAI_simulation)
LAI_simulation$Date<- as.numeric(LAI_simulation$Date,origin="2009-10-07")
#R does not see the origin
axis.Date(side=3,at=LAI_simulation$Date)
# also tried seq
dates <- seq(LAI_simulation$Date[1, "2009-10-07"], LAI_simulation$Date[nrow(LAI_simulation$Date), "2010-10-07"], by = "days")
</code>```

Thanks for your help.

答:
```<code>LAI_simulation$Date <- as.Date( LAI_simulation$Date, '%Y/%m/%d')
LAI_simulation$Date <- as.integer(LAI_simulation$Date - as.Date("2009-10-07"))
plot(LAI~Date,data=LAI_simulation,xlab="Days since Oct, 7, 2009",cex=0.3,cex.lab=1.2,xaxt="n",xaxs="i",yaxs="i",ylim=c(0,6))
axis(1,xlim=c(0,2200),xaxp=c(0,2200,11),cex.lab=1.2,cex.axis=0.8,xaxs="i")
LAI_simulation$Date<- as.Date(LAI_simulation$Date, origin="2009-10-07")
par(new=TRUE)
plot(LAI~Date, data=LAI_simulation,xlab="",ylab="",
     xaxt="n",type="p",cex=0.2,col=1,xaxs="i",yaxs="i",ylim=c(0,6))
axis.Date(side=3, at=seq(min(LAI_simulation$Date), max(LAI_simulation$Date),by="year"), format="%Y", xlab="xxx",cex.axis=0.9)
mtext("years",side=3,line=3,cex.lab=1.2)
</code>```

Body:
How can I convert date to continuous variable staring from 1. I tried as.numeric but R starts counting from default January 1, 1970 while my data start Oct 7, 2009.

I need to do this conversion to plot the date on two x-axes (1 and 3).

plot(LAI~Date, data=LAI_simulation)
LAI_simulation$Date<- as.numeric(LAI_simulation$Date,origin="2009-10-07")
#R does not see the origin
axis.Date(side=3,at=LAI_simulation$Date)
# also tried seq
dates <- seq(LAI_simulation$Date[1, "2009-10-07"], LAI_simulation$Date[nrow(LAI_simulation$Date), "2010-10-07"], by = "days")

Thanks for your help.


问:
fetch() with FormData
I am learning uploading files with Node.js and multer. I have configurated main app.js file, aswell as upload.html.

My form:

```<code><form id="uploadForm" action="/uploads" enctype="multipart/form-data" method="post">
    <input id="upload-input" type="file" name="uploads" multiple>
    <button class="upload-button" type="button">File</button>
</form>
</code>```

and script.js with which I am trying to handle form data and posting it with fetch():

```<code>uploadInput.addEventListener('change', function() {
    let files = event.target.files;

    if(files.length > 0) {
        let formData = new FormData();

        for(let i = 0; i < files.length; i++) {
            let file = files[i];

            formData.append('uploads', file);
        }

        fetch('uploads', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json(), error => error.message);
    }
});
</code>```

Files are uploading and everything is fine except two errors.
First displays at browser console:

```<code>uploader:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0
</code>```

And second in WebStorm IDE console:

```<code>(node:51729) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
</code>```

Do you have an idea why it's throwing with errors, while everything works fine?

答:
It looks like the problem is with .then(res => res.json(), error => error.message);

The JSON parsing error is almost certainly because you're not getting JSON back in your response. It's hard to tell why exactly you're getting the deprecation warning, but it may be related to your .then() call. For both, do something useful with the result, such as console.log(res) and console.log(error).

Title: fetch() with FormData

Body:
I am learning uploading files with Node.js and multer. I have configurated main app.js file, aswell as upload.html.

My form:

<form id="uploadForm" action="/uploads" enctype="multipart/form-data" method="post">
    <input id="upload-input" type="file" name="uploads" multiple>
    <button class="upload-button" type="button">File</button>
</form>

and script.js with which I am trying to handle form data and posting it with fetch():

uploadInput.addEventListener('change', function() {
    let files = event.target.files;

    if(files.length > 0) {
        let formData = new FormData();

        for(let i = 0; i < files.length; i++) {
            let file = files[i];

            formData.append('uploads', file);
        }

        fetch('uploads', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json(), error => error.message);
    }
});

Files are uploading and everything is fine except two errors.
First displays at browser console:

uploader:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

And second in WebStorm IDE console:

(node:51729) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

Do you have an idea why it's throwing with errors, while everything works fine?


问:
Mirth Custom Web Service Method
I was following mirth tutorials link : http://www.mirthcorp.com/community/wiki/display/mirth/Creating+a+custom+Web+Service+in+Mirth+Connect+3.0.1

My current mirth version is 3.5.x . Even downloaded donkey-server.jar and donkey-client.jar from mirth library. But when I import it I dont see the AcceptMessage and WebServiceReceiver class being resolved. When I verified in the jars the path com.mirth.connect.connectors.ws is not present.

Please let me which jar to be used to resolve this issue?

答: Those classes are in extensions/ws/ws-server.jar. You can add that to the classpath (with -cp) when compiling your code. More information here: http://www.mirthcorp.com/community/wiki/display/mirth/How+to+create+and+invoke+custom+Java+code+in+Mirth+Connect</p>

Title: Mirth Custom Web Service Method


问:
How to get Outlook Access token?
I'm using the outlook calendar rest api from Salesforce. To continuously leverage the calendar API I need to get authorisation code, access and refresh token.

I have been able to get the Authorisation code by hitting the API. How to get the access token using development code to use the outlook calendar rest API.

答:
Please find the list of AAD authentication libraries here:

https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-libraries

Title: How to get Outlook Access token?


问:
Unable to select input text box element in selenium java
I'm trying to get the data from the input text box and update without id and name. The following is the HTML code for that input tag. Here id, name and value changes from element to element.

```<code><input id="rgrdSearchResult_ctl00_ctl06_dtpLocalDateTime_dateInput" name="rgrdSearchResult$ctl00$ctl06$dtpLocalDateTime$dateInput" class="riTextBox riEnabled" value="03/06/2017 17:00" type="text">
</code>```

I tried the following code.

```<code>public String getDateTime(WebDriver driver){
    List<WebElement> lis = driver.findElements(By.className("riEnabled"));
    WebElement ele = lis.get(1);
    return ele.getAttribute("value");
}
</code>```

答:
I suspect the problem here is that By.className is looking for is the whole text "riTextBox riEnabled" (including the space character). It would probably work if you changed your selector to By.className("riTextBox riEnabled"), though I doubt that's what you want.

Try using By.cssSelector instead. There are multiple ways of doing it, for example:

```<code>By.cssSelector("input[contains(@class, 'riEnabled')]")

By.cssSelector("input[class*='riEnabled']")
</code>```

Body:
I'm trying to get the data from the input text box and update without id and name. The following is the HTML code for that input tag. Here id, name and value changes from element to element.

<input id="rgrdSearchResult_ctl00_ctl06_dtpLocalDateTime_dateInput" name="rgrdSearchResult$ctl00$ctl06$dtpLocalDateTime$dateInput" class="riTextBox riEnabled" value="03/06/2017 17:00" type="text">

I tried the following code.

public String getDateTime(WebDriver driver){
    List<WebElement> lis = driver.findElements(By.className("riEnabled"));
    WebElement ele = lis.get(1);
    return ele.getAttribute("value");
}

Body:
I suspect the problem here is that By.className is looking for is the whole text "riTextBox riEnabled" (including the space character). It would probably work if you changed your selector to By.className("riTextBox riEnabled"), though I doubt that's what you want.

Try using By.cssSelector instead. There are multiple ways of doing it, for example:

By.cssSelector("input[contains(@class, 'riEnabled')]")

By.cssSelector("input[class*='riEnabled']")


问:
localToGlobal not working - for reals though
I know there a bajillion threads on this topic, and maybe I am retarded, but this simply isn't working and I think I am missing something really key?

Lets say I have sprites _testTarget and _testParent nested like this.

```<code>_testParent = new Sprite();
this.addChild(_testParent);

_testTarget = new Sprite()
_testParent.addChild(_testParent);
</code>```

And lets say I want to get the global cords of _testTarget.  When I do localToGlobal I always get back 0,0 when I know for a fact its actual cords are like 200,100

```<code>var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.localToGlobal(point);  // returns 0,0

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.parent.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.parent.localToGlobal(point);  // Breaks, "parent" is null
</code>```

If it helps, this class/sprite instantiated inside of a sprite, inside of a sprite, inside of a sprite...etc and the reason its cords are 200,100 are because one of its parent containers is set to that - but I thought localToGlobal was supposed to go all the way to very top layer?  Help?

答:
In your first block, this wont work:

```<code>_testParent.addChild(_testParent);
</code>```

Because you can't add a display object as its own child.

Body:
I know there a bajillion threads on this topic, and maybe I am retarded, but this simply isn't working and I think I am missing something really key?

Lets say I have sprites _testTarget and _testParent nested like this.

_testParent = new Sprite();
this.addChild(_testParent);

_testTarget = new Sprite()
_testParent.addChild(_testParent);

And lets say I want to get the global cords of _testTarget.  When I do localToGlobal I always get back 0,0 when I know for a fact its actual cords are like 200,100

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.localToGlobal(point);  // returns 0,0

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.parent.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.parent.localToGlobal(point);  // Breaks, "parent" is null

If it helps, this class/sprite instantiated inside of a sprite, inside of a sprite, inside of a sprite...etc and the reason its cords are 200,100 are because one of its parent containers is set to that - but I thought localToGlobal was supposed to go all the way to very top layer?  Help?

Body:
In your first block, this wont work:

_testParent.addChild(_testParent);

Because you can't add a display object as its own child.


问:
What determines when a log4j TimeBasedRollingPolicy rolls over?
I'm setting up a TimeBasedRollingPolicy from Log4J Extras and I am not clear what tells the policy when to roll over.  The API is not explicit so I'm just making inferences.  It sounds like it's the last element in the FileNamePattern that determines the frequency.

Take this example from the log4j Wiki:

```<code><appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender">
    <!-- The active file to log to -->
    <param name="file" value="/applogs/myportal/portal.log" />
    <param name="append" value="true" />
    <param name="encoding" value="UTF-8" />

    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
    <!-- The file to roll to, this is a fairly intelligent parameter, if the file
         ends in .gz, it gzips it, based on the date stamp it rolls at that time,
         default is yyyy-MM-dd, (rolls at midnight)
    -->
        <param name="FileNamePattern" value="/applogs/myportal/portal.%d.log.gz" />
    </rollingPolicy>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
    </layout>
</appender>
</code>```

Am I to assume that because the pattern ends in dd, the policy is to roll when that changes?  Same with an example in the API, a pattern of yyyy-MM means the file should roll when MM changes?

Thanks!

Paul

答:
I got this working. Below is the code for log4j. You only need to add log4j-extras dependencies in pom.xml and use below code:
The below code rolls at every minutes and creates .zip file.

```<code><rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
    <param name="FileNamePattern" value="/opt/app/srdotcom/logs/portal.%d{yyyy-MM-dd-HH-mm}.log.zip" />
</rollingPolicy>

<layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{YYYY-MM-dd HH:mm:ss:SSS z}| %c{2}| %m%n" />
</layout>
</code>```

Maven Dependencies:

```<code>  <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>apache-log4j-extras</artifactId>
        <version>1.2.17</version>
    </dependency>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm setting up a TimeBasedRollingPolicy from Log4J Extras and I am not clear what tells the policy when to roll over.  The API is not explicit so I'm just making inferences.  It sounds like it's the last element in the FileNamePattern that determines the frequency.

Take this example from the log4j Wiki:

<appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender">

    <param name="file" value="/applogs/myportal/portal.log" />
    <param name="append" value="true" />
    <param name="encoding" value="UTF-8" />

    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">

        <param name="FileNamePattern" value="/applogs/myportal/portal.%d.log.gz" />
    </rollingPolicy>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
    </layout>
</appender>

Am I to assume that because the pattern ends in dd, the policy is to roll when that changes?  Same with an example in the API, a pattern of yyyy-MM means the file should roll when MM changes?

Thanks!

Paul

Body:
I got this working. Below is the code for log4j. You only need to add log4j-extras dependencies in pom.xml and use below code:
The below code rolls at every minutes and creates .zip file.

<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
    <param name="FileNamePattern" value="/opt/app/srdotcom/logs/portal.%d{yyyy-MM-dd-HH-mm}.log.zip" />
</rollingPolicy>

<layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{YYYY-MM-dd HH:mm:ss:SSS z}| %c{2}| %m%n" />
</layout>

Maven Dependencies:

  <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>apache-log4j-extras</artifactId>
        <version>1.2.17</version>
    </dependency>


问:
Javascript Variable Unchanged
```<code>let errors = false;

// Check for errors in any single payload
for (let result of results) if (result.status === "error") {
    errors = true;
    errorMessage = result.message;
    console.log(errors) // logs out "true"
} else {
    errors = false;
}

console.log(errors) // logs out "false"

// If error exists, alert user
if (errors === true) {
   console.log(errors);
   alert('Error Requesting Monitor Data!\n'+errorMessage)
} else {
    console.log(errors); // logs out "false"
}
</code>```

New to JavaScript, coming from Python/Scala. In the code above, errors outside of the for loop scope never modifies to true. What am I not understanding about the scope of variables and modification of values?

答:
Your loop is largely irrelevent.

Since you set errors = false in the else part of the loop, you are essentially checking to see if the last thing you test is an error.

You go through the loop and flip the result to true or false each time. It ends up with a value describing the last thing.

If your goal is to test if "one or more" of the collection is an error, then you need to remove the else branch.

That way it starts off as false and might get flipped to true if there are errors but will never get flipped back.

Title: Javascript Variable Unchanged

Body:
let errors = false;

// Check for errors in any single payload
for (let result of results) if (result.status === "error") {
    errors = true;
    errorMessage = result.message;
    console.log(errors) // logs out "true"
} else {
    errors = false;
}

console.log(errors) // logs out "false"

// If error exists, alert user
if (errors === true) {
   console.log(errors);
   alert('Error Requesting Monitor Data!\n'+errorMessage)
} else {
    console.log(errors); // logs out "false"
}

New to JavaScript, coming from Python/Scala. In the code above, errors outside of the for loop scope never modifies to true. What am I not understanding about the scope of variables and modification of values?


问:
Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine
I created a windows application developed in .NET 3.5 in a 32 bit Windows 2008 server. When deployed the application in a 64 bit server it shows the error "Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine ".

So as a solution to this issue, i have changed the build property of the project to X86, so that it will build in 32 bit mode, and rebuild the project in the 32bit machine. But, the same project uses other DB drivers (DB2, SQL etc.) to connect to other databases. So when i deployed my app again in the 64 bit OS, it throws the exception " Attempted to load a 64-bit assembly on a 32-bit platform. "

I am using the Microsoft.Jet.OLEDB.4.0 driver to read and write to the Excel (.xls)

答:
We have come across this issue in desktop app.

Dev Environment:
Windows 7 Ultimate - 64 bit
.Net Framework 4.5
Provider=Microsoft.Jet.OLEDB.4.0

It has been resolved by changing Platform target to X86 from Any CPU.
Project Properties >> Build >> Platform Target.


问:
Laravel: php artisan serve doesn't start
I've dug through a few of the other answers here and nothing seems to fit the bill. I'm probably going to leave some information out initially so just let me know what else you might need and thanks!

Currently running ubuntu 7, using composer and laravel both of which seem to be installed properly:

When I type 'php artisan serve' and 'php artisan serve --port:8000' into terminal I get this error:

PHP Warning:
  require(/home/user/Projects/thingy/bootstrap/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 PHP
  Fatal error:  require(): Failed opening required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17

When I attempt to run 'php -S localhost:8000 -t public/' just as an attempt I get the following error upon refresh:

PHP 7.0.18-0ubuntu0.17.04.1 Development Server started at Thu Jul  6
  09:15:36 2017 Listening on http://localhost:8000 Document root is
  /home/user/Projects/thingy/public Press Ctrl-C to quit. [Thu Jul  6
  09:15:40 2017] PHP Warning:
  require(/home/user/Projects/thingy/bootstrap/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 [Thu
  Jul  6 09:15:40 2017] PHP Fatal error:  require(): Failed opening
  required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 [Thu
  Jul  6 09:15:40 2017] 127.0.0.1:57214 [500]: / - require(): Failed
  opening required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17

I checked to see if maybe a server was already running using the 'ps -ef | grep php' command in terminal and I don't see any servers running at all.

I have run 'composer install' and I get the following error:

Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Cannot create cache
  directory /home/user/.composer/cache/files/, or directory is not
  writable. Proceeding without cache Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Loading composer
  repositories with package information Installing dependencies
  (including require-dev) from lock file Your requirements could not be
  resolved to an installable set of packages.

Problem 1
      - Installation request for laravel/framework v5.4.28 -> satisfiable by laravel/framework[v5.4.28].
      - laravel/framework v5.4.28 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

  Problem 2
      - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
      - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.   Problem 3
      - Installation request for phpunit/phpunit 5.7.21 -> satisfiable by phpunit/phpunit[5.7.21].
      - phpunit/phpunit 5.7.21 requires ext-dom * -> the requested PHP extension dom is missing from your system.   Problem 4
      - laravel/framework v5.4.28 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
      - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.28].
      - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].

To enable extensions, verify that they are enabled in your .ini
  files:
      - /etc/php/7.0/cli/php.ini
      - /etc/php/7.0/cli/conf.d/10-opcache.ini
      - /etc/php/7.0/cli/conf.d/10-pdo.ini
      - /etc/php/7.0/cli/conf.d/20-calendar.ini
      - /etc/php/7.0/cli/conf.d/20-ctype.ini
      - /etc/php/7.0/cli/conf.d/20-exif.ini
      - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
      - /etc/php/7.0/cli/conf.d/20-ftp.ini
      - /etc/php/7.0/cli/conf.d/20-gettext.ini
      - /etc/php/7.0/cli/conf.d/20-iconv.ini
      - /etc/php/7.0/cli/conf.d/20-json.ini
      - /etc/php/7.0/cli/conf.d/20-pdo_pgsql.ini
      - /etc/php/7.0/cli/conf.d/20-pgsql.ini
      - /etc/php/7.0/cli/conf.d/20-phar.ini
      - /etc/php/7.0/cli/conf.d/20-posix.ini
      - /etc/php/7.0/cli/conf.d/20-readline.ini
      - /etc/php/7.0/cli/conf.d/20-shmop.ini
      - /etc/php/7.0/cli/conf.d/20-sockets.ini
      - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
      - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
      - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
      - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
      - /etc/php/7.0/cli/conf.d/20-zip.ini   You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

When running 'composer dump-autoload' I get the following:

Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Cannot create cache
  directory /home/user/.composer/cache/files/, or directory is not
  writable. Proceeding without cache Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Generating optimized
  autoload files

After following the advice of Nishan Karunarathna and Alex I now get the following error when I run 'php artisan serve':

PHP Fatal error:  Uncaught Error: Class
  'Illuminate\Foundation\Application' not found in
  /home/joshua/Projects/thingy/bootstrap/app.php:14 Stack trace:

0 /home/joshua/Projects/thingy/artisan(18): require_once()

1 {main}   thrown in /home/joshua/Projects/thingy/bootstrap/app.php on line 14

Thanks for any help you give!

答:
Ok so I managed to answer my own question (actually a friend answered it for me.)

Apparently after you install laravel and composer it can, on occasion, lose the file path:

I had to open my .bashrc file in my hidden files on the /home/user/ level and add the command 'export PATH=~/.composer/vendor/bin:$PATH'

I think the other users here did contribute to fixing my problem as laravel and composer didn't seem to be installed correctly despite the files being in the proper place.


问:
Attach ChangeListener to multiple properties
I do have a model which consists of multiple observable SimpleDoubleProperty, i now have a program which runs a function depending on changes on the observable properties.

I now do have a function calculateThings which gets called on changes:

```<code>public double calculateThings() {
  return getA() + getB() + getC();
}
</code>```

For triggering that function i do attach a ChangeListener to every Property:

```<code>aProperty().addListener(observable -> calculateThings());
bProperty().addListener(observable -> calculateThings());
cProperty().addListener(observable -> calculateThings());
</code>```

Is there a possiblity to add a ChangeListener to multiple properties in order to simplify the change listening? The Bindings API is not suitable here, the calculations are rather complex.

Like:

```<code>commonObservable().addListener(observable -> calculateThings());
</code>```

答:
You can use the Bindings API for arbitrarily complex computations, for example using a custom binding:

```<code>DoubleBinding computed = new DoubleBinding() {
    {
        super.bind(aProperty, bProperty, cProperty);
    }

    @Override
    public double computeValue() {
        return getA() + getB() + getC() ;
    }
};
</code>```

or using the Bindings.createXXXBinding(...) utility methods:

```<code>DoubleBinding computed = Bindings.createDoubleBinding(
    () -> getA() + getB() + getC(),
    aProperty, bProperty, cProperty);
</code>```

In either case the binding will automatically update when any of the bound properties (aProperty, bProperty, or cProperty in the example) change, and you can either bind to computed or add listeners in the usual way:

```<code>someDoubleProperty.bind(computed);
computed.addListener((obs, oldComputedValue, newComputedValue) -> {
    /* some code */
});
</code>```

Body:
I do have a model which consists of multiple observable SimpleDoubleProperty, i now have a program which runs a function depending on changes on the observable properties.

I now do have a function calculateThings which gets called on changes:

public double calculateThings() {
  return getA() + getB() + getC();
}

For triggering that function i do attach a ChangeListener to every Property:

aProperty().addListener(observable -> calculateThings());
bProperty().addListener(observable -> calculateThings());
cProperty().addListener(observable -> calculateThings());

Is there a possiblity to add a ChangeListener to multiple properties in order to simplify the change listening? The Bindings API is not suitable here, the calculations are rather complex.

Like:

commonObservable().addListener(observable -> calculateThings());

Body:
You can use the Bindings API for arbitrarily complex computations, for example using a custom binding:

DoubleBinding computed = new DoubleBinding() {
    {
        super.bind(aProperty, bProperty, cProperty);
    }

    @Override
    public double computeValue() {
        return getA() + getB() + getC() ;
    }
};

or using the Bindings.createXXXBinding(...) utility methods:

DoubleBinding computed = Bindings.createDoubleBinding(
    () -> getA() + getB() + getC(),
    aProperty, bProperty, cProperty);

In either case the binding will automatically update when any of the bound properties (aProperty, bProperty, or cProperty in the example) change, and you can either bind to computed or add listeners in the usual way:

someDoubleProperty.bind(computed);
computed.addListener((obs, oldComputedValue, newComputedValue) -> {
    /* some code */
});


问:
MAMP Virtual Hosts not working properly, loading 'It Works!' page
I had an issue last night where MAMP just refused to connect to the Apache server(unsure whether this has something to do with my issue). I decided to uninstall and reinstall. I was able to connect once again, however, when I added my virtual host to the httpd-vhosts.conf file in my MAMP folder, and navigate to it I get brought to a 'It works!' page.  (I also realised I get this page by typing localhost even without running MAMP?)

Below are some of my files

httpd.conf(in MAMP)

```<code>//Uncommented line below
# Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf
</code>```

httpd.conf(in MAMP)

```<code>NameVirtualHost *:80

<VirtualHost *:80>
    ServerName portfolio
    DocumentRoot '/Applications/MAMP/htdocs/portfolio'
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot '/Applications/MAMP/htdocs'
    ServerName localhost
</VirtualHost>
</code>```

/private/etc/hosts

```<code>##
# Host Database
# localhost is used to configure the lookback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost
127.0.0.1       portfolio
</code>```

This is a copy paste of what I had before which worked 100%, unsure what happened between MAMP stopping working, the uninstall and reinstall. Is there an issue with apache somehow overwriting something? Really out of my depth here with this issue. Is there somewhere else I should be looking to debug this?

For reference, localhost:8888 & localhost:8888/portfolio work as expected, localhost/ & portfolio/ don't, brings me to the 'It works!' page. Before this issue I was able to do 'localhost/phpmyadmin' to bring me to phpmyadmin and 'localhost/portfolio' to bring me to that directory, but neither of those work either. I've been wracking me brain for hours over this, watching tutorials and reading other answers but to no avail.

Anyone have any idea why this is occuring? Any help would be greatly appreciated.

答:
So I eventually figured it out if anyone else has the same issue. I had forgotten previously that I had my localhost running on port 80. However when I tried that before my apache server wouldn't start on MAMP, the reason being was due to port 80 being used by /private/etc/apache2, so I used the answer to this question

https://superuser.com/questions/986775/how-can-i-remove-apache2-that-i-have-installed-in-mac-os-x

to remove apache. (Alternatively I guess you could just change the port number it listens to in the httpd.conf files?) I then changed my MAMP to listen to port 80 and this fixed my problem. Hope this helps anyone else with same issue

Body:
I had an issue last night where MAMP just refused to connect to the Apache server(unsure whether this has something to do with my issue). I decided to uninstall and reinstall. I was able to connect once again, however, when I added my virtual host to the httpd-vhosts.conf file in my MAMP folder, and navigate to it I get brought to a 'It works!' page.  (I also realised I get this page by typing localhost even without running MAMP?)

Below are some of my files

httpd.conf(in MAMP)

//Uncommented line below
# Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

httpd.conf(in MAMP)

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName portfolio
    DocumentRoot '/Applications/MAMP/htdocs/portfolio'
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot '/Applications/MAMP/htdocs'
    ServerName localhost
</VirtualHost>

/private/etc/hosts

##
# Host Database
# localhost is used to configure the lookback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost
127.0.0.1       portfolio

This is a copy paste of what I had before which worked 100%, unsure what happened between MAMP stopping working, the uninstall and reinstall. Is there an issue with apache somehow overwriting something? Really out of my depth here with this issue. Is there somewhere else I should be looking to debug this?

For reference, localhost:8888 & localhost:8888/portfolio work as expected, localhost/ & portfolio/ don't, brings me to the 'It works!' page. Before this issue I was able to do 'localhost/phpmyadmin' to bring me to phpmyadmin and 'localhost/portfolio' to bring me to that directory, but neither of those work either. I've been wracking me brain for hours over this, watching tutorials and reading other answers but to no avail.

Anyone have any idea why this is occuring? Any help would be greatly appreciated.


问:
CSS layout with header and colums top to bottom
Greets,

I'm currently working on a website and have stumbled upon some layout difficulties. What I want is a website with a header (fixed hight) and followed by three columns (left, middle, left). I want the columns to stretch from top to bottom. But when I set them to a 100% height, the page gets overflow from the static header on 140px. I have included an image of the page with lots of colors to show the divs (http://oi51.tinypic.com/974rqd.jpg).

Any help is greatly appreciated!

答:
Set a background image that repeats vertically. Either one image for each section, or easier yet, a single image that contains the dividers of all 3 sections.

See here for an example of this being done.


问:
Java: number of lines in a file without processing it
I need to know the number of lines of a file before processing it, because I need to know the number of lines before read it, or in the worst case escenario read it twice..... so I made this code but It not works.. so maybe is just not possible ?

```<code>InputStream inputStream2 = getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));

String line;
int numLines = 0;
while ((line = reader.readLine()) != null) {
        numLines++;
}

TextFileDataCollection dataCollection = new TextFileDataCollection (numLines, 50);

BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream2));

while ((line = reader2.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(reader2.readLine(), ",");
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());
        }
}
</code>```

答:
Here's a similar question with java code, although it's a bit older:

Number of lines in a file in Java

```<code>public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}
</code>```

EDIT:

Here's a reference related to inputstreams specifically:

From Total number of rows in an InputStream (or CsvMapper) in Java

"Unless you know the row count ahead of time, it is not possible without looping. You have to read that file in its entirety to know how many lines are in it, and neither InputStream nor CsvMapper have a means of reading ahead and abstracting that for you (they are both stream oriented interfaces).

None of the interfaces that ObjectReader can operate on support querying the underlying file size (if it's a file) or number of bytes read so far.

One possible option is to create your own custom InputStream that also provides methods for grabbing the total size and number of bytes read so far, e.g. if it is reading from a file, it can expose the underlying File.length() and also track the number of bytes read. This may not be entirely accurate, especially if Jackson buffers far ahead, but it could get you something at least."

Body:
I need to know the number of lines of a file before processing it, because I need to know the number of lines before read it, or in the worst case escenario read it twice..... so I made this code but It not works.. so maybe is just not possible ?

InputStream inputStream2 = getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));

String line;
int numLines = 0;
while ((line = reader.readLine()) != null) {
        numLines++;
}

TextFileDataCollection dataCollection = new TextFileDataCollection (numLines, 50);

BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream2));

while ((line = reader2.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(reader2.readLine(), ",");
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());
        }
}

Body:
Here's a similar question with java code, although it's a bit older:

Number of lines in a file in Java

public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

EDIT:

Here's a reference related to inputstreams specifically:

From Total number of rows in an InputStream (or CsvMapper) in Java

"Unless you know the row count ahead of time, it is not possible without looping. You have to read that file in its entirety to know how many lines are in it, and neither InputStream nor CsvMapper have a means of reading ahead and abstracting that for you (they are both stream oriented interfaces).

None of the interfaces that ObjectReader can operate on support querying the underlying file size (if it's a file) or number of bytes read so far.

One possible option is to create your own custom InputStream that also provides methods for grabbing the total size and number of bytes read so far, e.g. if it is reading from a file, it can expose the underlying File.length() and also track the number of bytes read. This may not be entirely accurate, especially if Jackson buffers far ahead, but it could get you something at least."


问:
Simple VBA to Select a Range from First .Find Value?
I want to locate a value within column "A" then select from that address to the first blank row encountered. Here is what I have, but Set f isn't working. My Set c works and returns $A$32, which is the correct address. What am I missing?</p>

```<code>With Workbooks("MyBook").Sheets("Mysheet")
    Set c = .Range("$A:$A").Find("Red Car").Offset(2, 0)
    Set f = .Range(c.Address & Range("A").End(xlDown).Row)
End With
</code>```

答:
Try this, and check first that the search term is found</p>

```<code>With Workbooks("MyBook").Sheets("Mysheet")
    Set c = .Range("$A:$A").Find("Red Car")
    If Not c Is Nothing Then Set f = Range(c.Offset(2, 0), c.Offset(2, 0).End(xlDown))
End With
</code>```

Body:
I want to locate a value within column "A" then select from that address to the first blank row encountered. Here is what I have, but Set f isn't working. My Set c works and returns $A$32, which is the correct address. What am I missing?

With Workbooks("MyBook").Sheets("Mysheet")
    Set c = .Range("$A:$A").Find("Red Car").Offset(2, 0)
    Set f = .Range(c.Address & Range("A").End(xlDown).Row)
End With

Body:
Try this, and check first that the search term is found

With Workbooks("MyBook").Sheets("Mysheet")
    Set c = .Range("$A:$A").Find("Red Car")
    If Not c Is Nothing Then Set f = Range(c.Offset(2, 0), c.Offset(2, 0).End(xlDown))
End With


问:
Dynamically adding views to CardView without duplicating
I have a layout for CardView with 2 TextViews and 2 Buttons initially. Based on the #options in poll.getOptions(), a Cardview can have up to 5 buttons. So I want to add dynamically those buttons... If I add them in onBindViewHolder, after clicking a button, it adds duplicates of these buttons. I tried to add it in onCreateViewHolder but when I try to create a new button it gives me a NullPointerException. I tried in many ways but can't find solution. What is the true way of adding dynamic views in cardview or why it gives me that error?

Layout for CardView:

```<code><?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto">

        <data>
            <variable
                name = "poll"
                type = "mattoncino.pollo.Poll" />
        </data>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            card_view:cardCornerRadius="@dimen/cardview_default_radius"
            card_view:cardElevation="@dimen/cardview_default_elevation">

            <LinearLayout
                android:id="@+id/listItemLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="5dp">

                <TextView
                    android:id="@+id/nameTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="30sp"
                    android:textAllCaps="false"
                    android:text="@{poll.name}"/>

                <TextView
                    android:id="@+id/questionTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    android:text="@{poll.question}"/>

                <Button
                    android:id="@+id/opt1Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(1)}"
                    android:enabled="@{!poll.disabled}"/>

                <Button
                    android:id="@+id/opt2Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(2)}"
                    android:enabled="@{!poll.disabled}"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>
    </layout>
</code>```

My CardViewAdapter class:

```<code>public class PollsCardViewAdapter extends RecyclerView.Adapter<PollsCardViewAdapter.CardViewHolder> {

        private List<Poll> activePolls;
        private final static String TAG = "CARDVIEW_ADAPTER";

        public PollsCardViewAdapter(List<Poll> polls){
            activePolls = polls;
        }

        public static class CardViewHolder extends RecyclerView.ViewHolder {

            private ActivePollsListItemBinding listItemBinding;

            public CardViewHolder(View v) {
                super(v);
                listItemBinding = DataBindingUtil.bind(v);
            }

            public ActivePollsListItemBinding getBinding(){
                return listItemBinding;
            }
        }

        // Create new views (invoked by the layout manager)
        @Override
        public PollsCardViewAdapter.CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.active_polls_list_item, parent, false);

            CardViewHolder holder = new CardViewHolder(v);
            Context context = holder.getBinding().nameTextView.getContext();

            Poll poll = activePolls.get(viewType);

            for (int i = 2; i < poll.getOptions().size(); i++) {
                int opt = i + 1;
                Button button = createNewOptionButton(context, poll.getText(opt));
                if(poll.isDisabled()) {
                    button.setEnabled(false);
                }
                else button.setText(poll.getText(opt));
                parent.addView(button);
            }

            return holder;
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(final PollsCardViewAdapter.CardViewHolder holder, final int position) {
            final Poll poll = activePolls.get(position);
            final LinearLayout rLayout = holder.getBinding().listItemLayout;

            if(!poll.isDisabled()){
                for (int i = 2; i < rLayout.getChildCount(); i++){
                    final View view = rLayout.getChildAt(i);
                    final int opt = i - 1;

                    if(view instanceof Button){
                        final Button button = (Button) view;
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                button.setText(button.getText().toString() + "    " + "\u2713");
                             setCardDetails(holder.getBinding().nameTextView.getContext(), rLayout, poll, opt);
                            }
                        });
                    }
                }
            }

            holder.getBinding().setVariable(BR.poll, poll);
            holder.getBinding().executePendingBindings();
        }

        private void setCardDetails(final Context context, final LinearLayout rLayout, final Poll poll, final int opt){
            poll.setDisabled(true);
            disableOptionButtons(rLayout);
            rLayout.addView(addMessageView(context));

            Handler handler = new Handler();
            final Runnable r = new Runnable(){
                @Override
                public void run() {
                    poll.addVote(opt);
                    notifyDataSetChanged();
                }
            };
            handler.post(r);
        }

        private void disableOptionButtons(ViewGroup layout){
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                if(child.hasOnClickListeners())
                    child.setEnabled(false);
            }
        }

        private TextView addMessageView(Context context){
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            TextView textView = new TextView(context);
            textView.setLayoutParams(lparams);
            textView.setId(View.generateViewId());
            textView.setText("Thanks for voting! Wait for results...");
            textView.setTextSize(20);
            textView.setTypeface(null, Typeface.BOLD_ITALIC);

            return textView;
        }

        private static Button createNewOptionButton(Context context, String option) {
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            final Button button = new Button(context);
            button.setLayoutParams(lparams);
            button.setId(View.generateViewId());
            button.setTextSize(18);
            button.setText(option);
            //button.setBackgroundColor(Color.TRANSPARENT);
            return button;

        }

        @Override
        public int getItemCount() {
            return activePolls.size();
        }
    }
</code>```

The exception that I get, inside the createNewOptionButton()

```<code>mattoncino.pollo E/AndroidRuntime: FATAL EXCEPTION: main
        Process: mattoncino.pollo, PID: 4684
        java.lang.NullPointerException
        at android.support.v7.widget.RecyclerView$LayoutParams.getViewLayoutPosition(RecyclerView.java:10862)
        at android.support.v7.widget.RecyclerView$LayoutManager.getPosition(RecyclerView.java:7949)
        at android.support.v7.widget.LinearLayoutManager.updateLayoutState(LinearLayoutManager.java:1184)
        at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1323)
        at android.support.v7.widget.LinearLayoutManager.fixLayoutEndGap(LinearLayoutManager.java:894)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:636)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1160)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5333)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I think the safest bet would be to add all 5 buttons in the layout xml, and have them with

```<code>android:visibility="gone"
</code>```

so they don't appear.

Then in onBindViewHolder you can check the number of buttons needed, and modify the visibility accordingly, using View.setVisibility()

Sample code:

```<code>@Override
public void onBindViewHolder(final PollsCardViewAdapter.CardViewHolder holder, final int position) {
    ...

    int numOfButtons = poll.getOptions().size();
    for (int i = 0; i < 5; i++) {
        Button b = holder.buttons[i];
        if (i < numOfButtons) {
            b.setVisibility(View.VISIBLE);
            // configure button's text and whatever
        } else {
            b.setVisibility(View.GONE);
        }
    }

    ...
}
</code>```

Body:
I have a layout for CardView with 2 TextViews and 2 Buttons initially. Based on the #options in poll.getOptions(), a Cardview can have up to 5 buttons. So I want to add dynamically those buttons... If I add them in onBindViewHolder, after clicking a button, it adds duplicates of these buttons. I tried to add it in onCreateViewHolder but when I try to create a new button it gives me a NullPointerException. I tried in many ways but can't find solution. What is the true way of adding dynamic views in cardview or why it gives me that error?

Layout for CardView:

<?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto">

        <data>
            <variable
                name = "poll"
                type = "mattoncino.pollo.Poll" />
        </data>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            card_view:cardCornerRadius="@dimen/cardview_default_radius"
            card_view:cardElevation="@dimen/cardview_default_elevation">

            <LinearLayout
                android:id="@+id/listItemLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="5dp">

                <TextView
                    android:id="@+id/nameTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="30sp"
                    android:textAllCaps="false"
                    android:text="@{poll.name}"/>

                <TextView
                    android:id="@+id/questionTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    android:text="@{poll.question}"/>

                <Button
                    android:id="@+id/opt1Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(1)}"
                    android:enabled="@{!poll.disabled}"/>

                <Button
                    android:id="@+id/opt2Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(2)}"
                    android:enabled="@{!poll.disabled}"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>
    </layout>

My CardViewAdapter class:

public class PollsCardViewAdapter extends RecyclerView.Adapter<PollsCardViewAdapter.CardViewHolder> {

        private List<Poll> activePolls;
        private final static String TAG = "CARDVIEW_ADAPTER";

        public PollsCardViewAdapter(List<Poll> polls){
            activePolls = polls;
        }

        public static class CardViewHolder extends RecyclerView.ViewHolder {

            private ActivePollsListItemBinding listItemBinding;

            public CardViewHolder(View v) {
                super(v);
                listItemBinding = DataBindingUtil.bind(v);
            }

            public ActivePollsListItemBinding getBinding(){
                return listItemBinding;
            }
        }

        // Create new views (invoked by the layout manager)
        @Override
        public PollsCardViewAdapter.CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.active_polls_list_item, parent, false);

            CardViewHolder holder = new CardViewHolder(v);
            Context context = holder.getBinding().nameTextView.getContext();

            Poll poll = activePolls.get(viewType);

            for (int i = 2; i < poll.getOptions().size(); i++) {
                int opt = i + 1;
                Button button = createNewOptionButton(context, poll.getText(opt));
                if(poll.isDisabled()) {
                    button.setEnabled(false);
                }
                else button.setText(poll.getText(opt));
                parent.addView(button);
            }

            return holder;
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(final PollsCardViewAdapter.CardViewHolder holder, final int position) {
            final Poll poll = activePolls.get(position);
            final LinearLayout rLayout = holder.getBinding().listItemLayout;

            if(!poll.isDisabled()){
                for (int i = 2; i < rLayout.getChildCount(); i++){
                    final View view = rLayout.getChildAt(i);
                    final int opt = i - 1;

                    if(view instanceof Button){
                        final Button button = (Button) view;
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                button.setText(button.getText().toString() + "    " + "\u2713");
                             setCardDetails(holder.getBinding().nameTextView.getContext(), rLayout, poll, opt);
                            }
                        });
                    }
                }
            }

            holder.getBinding().setVariable(BR.poll, poll);
            holder.getBinding().executePendingBindings();
        }

        private void setCardDetails(final Context context, final LinearLayout rLayout, final Poll poll, final int opt){
            poll.setDisabled(true);
            disableOptionButtons(rLayout);
            rLayout.addView(addMessageView(context));

            Handler handler = new Handler();
            final Runnable r = new Runnable(){
                @Override
                public void run() {
                    poll.addVote(opt);
                    notifyDataSetChanged();
                }
            };
            handler.post(r);
        }

        private void disableOptionButtons(ViewGroup layout){
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                if(child.hasOnClickListeners())
                    child.setEnabled(false);
            }
        }

        private TextView addMessageView(Context context){
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            TextView textView = new TextView(context);
            textView.setLayoutParams(lparams);
            textView.setId(View.generateViewId());
            textView.setText("Thanks for voting! Wait for results...");
            textView.setTextSize(20);
            textView.setTypeface(null, Typeface.BOLD_ITALIC);

            return textView;
        }

        private static Button createNewOptionButton(Context context, String option) {
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            final Button button = new Button(context);
            button.setLayoutParams(lparams);
            button.setId(View.generateViewId());
            button.setTextSize(18);
            button.setText(option);
            //button.setBackgroundColor(Color.TRANSPARENT);
            return button;

        }

        @Override
        public int getItemCount() {
            return activePolls.size();
        }
    }

The exception that I get, inside the createNewOptionButton()

mattoncino.pollo E/AndroidRuntime: FATAL EXCEPTION: main
        Process: mattoncino.pollo, PID: 4684
        java.lang.NullPointerException
        at android.support.v7.widget.RecyclerView$LayoutParams.getViewLayoutPosition(RecyclerView.java:10862)
        at android.support.v7.widget.RecyclerView$LayoutManager.getPosition(RecyclerView.java:7949)
        at android.support.v7.widget.LinearLayoutManager.updateLayoutState(LinearLayoutManager.java:1184)
        at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1323)
        at android.support.v7.widget.LinearLayoutManager.fixLayoutEndGap(LinearLayoutManager.java:894)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:636)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1160)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5333)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)

Body:
I think the safest bet would be to add all 5 buttons in the layout xml, and have them with

android:visibility="gone"

so they don't appear.

Then in onBindViewHolder you can check the number of buttons needed, and modify the visibility accordingly, using View.setVisibility()

Sample code:

@Override
public void onBindViewHolder(final PollsCardViewAdapter.CardViewHolder holder, final int position) {
    ...

    int numOfButtons = poll.getOptions().size();
    for (int i = 0; i < 5; i++) {
        Button b = holder.buttons[i];
        if (i < numOfButtons) {
            b.setVisibility(View.VISIBLE);
            // configure button's text and whatever
        } else {
            b.setVisibility(View.GONE);
        }
    }

    ...
}


问:
Can I make a button/icon in a MFC toolbar that can't be clicked?
I have a subclass of CMFCToolBar that contains a few buttons, one for toggling a setting and the others for displaying the current state (shown one at a time). I need the other buttons to not be clickable- if the user clicks on them, they should not depress. Is there a way to prevent a button from depressing without making it disabled (because then it is grayed out) or to add an icon to a toolbar that has no interaction?</p>

答: Would it be easier - and potentially saner - to just handle the button press event and reset the button state, and then do nothing</p>


问:
Google script getting error while putting multiple conditions
I have pasted example below

code:

```<code>    function ck() {

    //assigning variables

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var lastrow = ss.getLastRow();
    var valsr7 = sheet.getRange(lastrow, 3).getValue();
    var valsr30 = sheet.getRange(lastrow, 4).getValue();
    var valsrn = sheet.getRange(lastrow, 5).getValue();
    var valINC7 = sheet.getRange(lastrow, 6).getValue();
    var valINC30 = sheet.getRange(lastrow, 7).getValue();
    var valINCn = sheet.getRange(lastrow, 8).getValue();
    var service = sheet.getRange(lastrow, 2).getValue();
    var now = new Date();
    var wk = now.getWeek();

    //now assigning values to variable
    var A = valsr7;
    var B = valsr30;
    var C = valsrn;
    var D = valINC7;
    var E = valINC30;
    var F = valINCn;
    var AB = AB;

    if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 ){
    MailApp.sendEmail({
    to: "prathamesh.padosakar.ext@lafargeholcim.com",
    subject : "Open Tickets Global-C&k-T2 - Week-"+wk+"",
    htmlBody: "Dear ABC, "+

    "<p>Not assigned to any one = "+C+""+

    "<P>   "+" "+

    "<p>Not updated more than 7 Days = "+D+" "+
    "<p>Not Updated more than 30 Days = "+E+""+
    "<p>Not assigned to any one = "+F+""+

    "<p>   "+" "+
           "<p>Best Regards,"+
          "<br>Global Service Desk "+,
    cc: "techno.pratham94@gmail.com"})
  }

    if(service == 'Global-Servicenow-Support-T2' && A == 0){

    MailApp.sendEmail({
    to: "prathamesh.padosakar.ext@lafargeholcim.com",
    subject : "Open Tickets Global-C&k-T2 - Week-"+wk+"",
    htmlBody: "Dear ABC, "+

    "<p>Not Updated more than 30 Days = "+B+""+
    "<p>Not assigned to any one = "+C+""+

    "<P>   "+" "+

    "<p>Not updated more than 7 Days = "+D+" "+
    "<p>Not Updated more than 30 Days = "+E+""+
    "<p>Not assigned to any one = "+F+""+

    "<p>   "+" "+
    "<p>Best Regards,"+
    "<br>Global Service Desk "+,
    cc: "techno.pratham94@gmail.com"
                      });

    }
    else {

   }
    if(service == 'Global-Servicenow-Support-T2' && B == 0){
    MailApp.sendEmail({
    to: "prathamesh.padosakar.ext@lafargeholcim.com",
    subject : "Open Tickets Global-C&k-T2 - Week-"+wk+"",
    htmlBody: "Dear ABC, "+

    "<p>Not updated more than 7 Days = "+A+" "+

    "<p>Not assigned to any one = "+C+""+

    "<P>   "+" "+

    "<p>Not updated more than 7 Days = "+D+" "+
    "<p>Not Updated more than 30 Days = "+E+""+
    "<p>Not assigned to any one = "+F+""+

    "<p>   "+" "+
    "<p>Best Regards,"+
    "<br>Global Service Desk "+,

    cc: "techno.pratham94@gmail.com"
    });

  }

    else {

  }
</code>```

when i pass condition through if(service == 'Global-Servicenow-Support-T2' && A == 0) and if(service == 'Global-Servicenow-Support-T2' && B == 0) it gives me single output output or correct output . when i pass condition if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 ) it give me output of all 3 conditions which are mention below.

if(service == 'Global-Servicenow-Support-T2' && A == 0) and if(service == 'Global-Servicenow-Support-T2' && B == 0) and if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 )

Please help i want single output when i pass condition if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 ).

答:
Change condition

```<code>if(service == 'Global-Servicenow-Support-T2' && A == 0){
</code>```

to

```<code>if(service == 'Global-Servicenow-Support-T2' && A == 0 && B != 0){
</code>```

and change condition

```<code>if(service == 'Global-Servicenow-Support-T2' && B == 0){
</code>```

to

```<code>if(service == 'Global-Servicenow-Support-T2' && B == 0 && A != 0){
</code>```

Then you will have one output for if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 )

Body:
I have pasted example below

code:

    function ck() {

    //assigning variables

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var lastrow = ss.getLastRow();
    var valsr7 = sheet.getRange(lastrow, 3).getValue();
    var valsr30 = sheet.getRange(lastrow, 4).getValue();
    var valsrn = sheet.getRange(lastrow, 5).getValue();
    var valINC7 = sheet.getRange(lastrow, 6).getValue();
    var valINC30 = sheet.getRange(lastrow, 7).getValue();
    var valINCn = sheet.getRange(lastrow, 8).getValue();
    var service = sheet.getRange(lastrow, 2).getValue();
    var now = new Date();
    var wk = now.getWeek();

    //now assigning values to variable
    var A = valsr7;
    var B = valsr30;
    var C = valsrn;
    var D = valINC7;
    var E = valINC30;
    var F = valINCn;
    var AB = AB;

    if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 ){
    MailApp.sendEmail({
    to: "prathamesh.padosakar.ext@lafargeholcim.com",
    subject : "Open Tickets Global-C&k-T2 - Week-"+wk+"",
    htmlBody: "Dear ABC, "+

    "
Not assigned to any one = "+C+""+

    "
   "+" "+

    "
Not updated more than 7 Days = "+D+" "+
    "
Not Updated more than 30 Days = "+E+""+
    "
Not assigned to any one = "+F+""+

    "
   "+" "+
           "
Best Regards,"+
          "
Global Service Desk "+,
    cc: "techno.pratham94@gmail.com"})
  }

    if(service == 'Global-Servicenow-Support-T2' && A == 0){

    MailApp.sendEmail({
    to: "prathamesh.padosakar.ext@lafargeholcim.com",
    subject : "Open Tickets Global-C&k-T2 - Week-"+wk+"",
    htmlBody: "Dear ABC, "+

    "
Not Updated more than 30 Days = "+B+""+
    "
Not assigned to any one = "+C+""+

    "
   "+" "+

    "
Not updated more than 7 Days = "+D+" "+
    "
Not Updated more than 30 Days = "+E+""+
    "
Not assigned to any one = "+F+""+

    "
   "+" "+
    "
Best Regards,"+
    "
Global Service Desk "+,
    cc: "techno.pratham94@gmail.com"
                      });

    }
    else {

   }
    if(service == 'Global-Servicenow-Support-T2' && B == 0){
    MailApp.sendEmail({
    to: "prathamesh.padosakar.ext@lafargeholcim.com",
    subject : "Open Tickets Global-C&k-T2 - Week-"+wk+"",
    htmlBody: "Dear ABC, "+

    "
Not updated more than 7 Days = "+A+" "+

    "
Not assigned to any one = "+C+""+

    "
   "+" "+

    "
Not updated more than 7 Days = "+D+" "+
    "
Not Updated more than 30 Days = "+E+""+
    "
Not assigned to any one = "+F+""+

    "
   "+" "+
    "
Best Regards,"+
    "
Global Service Desk "+,

    cc: "techno.pratham94@gmail.com"
    });

  }

    else {

  }

when i pass condition through if(service == 'Global-Servicenow-Support-T2' && A == 0) and if(service == 'Global-Servicenow-Support-T2' && B == 0) it gives me single output output or correct output . when i pass condition if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 ) it give me output of all 3 conditions which are mention below.

if(service == 'Global-Servicenow-Support-T2' && A == 0) and if(service == 'Global-Servicenow-Support-T2' && B == 0) and if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 )

Please help i want single output when i pass condition if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 ).

Body:
Change condition

if(service == 'Global-Servicenow-Support-T2' && A == 0){

to

if(service == 'Global-Servicenow-Support-T2' && A == 0 && B != 0){

and change condition

if(service == 'Global-Servicenow-Support-T2' && B == 0){

to

if(service == 'Global-Servicenow-Support-T2' && B == 0 && A != 0){

Then you will have one output for if (service == 'Global-Servicenow-Support-T2' && A ==0 && B == 0 )


问:
How to mark a directory as library root?
I've 2 projects in PhpStorm: one is working well while another won't work and I can't figure what make the first one working.

The first one is working well with library root for bower, npm and composer :

The second one is bower, npm are not detected as library root :

So the behaviour in PhpStorm is different, when I use the navigate file on second project, I see all the vendor file by default :

If I mark the directory as excluded, the ide don't understand the vendor class :

So how can we configure the IDE to mark a directory as library root ?

答: Thanks to @LazyOne comment, found the solution : Select Preferences | Languages & Frameworks | JavaScript | Libraries and click Add. Select the path you want to add and the folder will be marked as library root. Really useful for non standard path (not bower_components for example)</p>