text:
Q: Spring Web Services - Exception Skipping ExceptionResolver I have a SOAP service, the request and responses work as expected with good input, if I specify bad input for an XML element
in request body:
...
<ns:myIntegerElement>asdf</ns:myIntegerElement>
...

my exception resolver is invoked, this resolver is just an implementation of the exception resolver, so it doesn't have exception mappings, just a few System.out's in the abstract method
<bean id="exceptionResolver" class="com.mycompany.ws.MyExceptionResolver">

however, if I send a request that looks more like this:
...
    <ns:myIntegSOMETHINGGOTTOTALLYMESSUP!!!ent>asdf</ns:myIntegerElement>
...

my resolver isn't executed at all
I setup log4j to have a root debug level and see this output:

2010-08-09 10:30:01,900
  [Thread:http-8080-2] DEBUG
  [org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter]
  - Accepting incoming [org.springframework.ws.transport.http.HttpServletConnection@c46dcf]
  to
  [http://localhost:8080/myws/MyWebServices/]
  ERROR:  'The element type
  "ns:MESSEDUPELEMENT" must be terminated by
  the matching end-tag
  "".' 2010-08-09
  10:30:01,920 [Thread:http-8080-2]
  DEBUG
  [org.springframework.ws.transport.http.MessageDispatcherServlet]
  - Could not complete request org.springframework.ws.soap.saaj.SaajSoapMessageException:
  Could not access envelope: Unable to
  create envelope from given source: ;
  nested exception is
  com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl:
  Unable to create envelope from given
  source:
          at org.springframework.ws.soap.saaj.support.SaajUtils.getSaajVersion(SaajUtils.java:162)
          at org.springframework.ws.soap.saaj.SaajSoapMessage.getImplementation(SaajSoapMessage.java:251)
          at org.springframework.ws.soap.saaj.SaajSoapMessage.(SaajSoapMessage.java:84)
          at org.springframework.ws.soap.saaj.SaajSoapMessage.(SaajSoapMessage.java:70)
          at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java:168)
          at org.springframework.ws.transport.AbstractWebServiceConnection.receive(AbstractWebServiceConnection.java:90)
          at org.springframework.ws.transport.support.WebServiceMessageReceiverObjectSupport.handleConnection(WebServiceMessageReceiverObjectSupport.java:86)
          at org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter.handle(WebServiceMessageReceiverHandlerAdapter.java:57)
          at org.springframework.ws.transport.http.MessageDispatcherServlet.doService(MessageDispatcherServlet.java:230)
          at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
          at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:511)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
          at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
          at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
          at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
          at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
          at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
          at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
          at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
          at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
          at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
          at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
          at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
          at java.lang.Thread.run(Thread.java:619)
  Caused by:
  com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl:
  Unable to create envelope from given
  source:
          at com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:114)
          at com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPPart1_1Impl.createEnvelopeFromSource(SOAPPart1_1Impl.java:70)
          at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.getEnvelope(SOAPPartImpl.java:122)
          at org.springframework.ws.soap.saaj.support.SaajUtils.getSaajVersion(SaajUtils.java:159)
          ... 24 more Caused by: javax.xml.transform.TransformerException:
  org.xml.sax.SAXParseException: The
  element type "smm:smm-aid" must be
  terminated by the matching end-tag
  "".
          at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:719)
          at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:313)
          at com.sun.xml.internal.messaging.saaj.util.transform.EfficientStreamingTransformer.transform(EfficientStreamingTransformer.java:393)
          at com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:102)
          ... 27 more Caused by: org.xml.sax.SAXParseException: The
  element type "smm:smm-aid" must be
  terminated by the matching end-tag
  "".
          at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1231)
          at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
          at org.xml.sax.helpers.XMLFilterImpl.parse(XMLFilterImpl.java:333)
          at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(TransformerImpl.java:636)
          at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:707)
          ... 30 more

It appears that spring is missing a possible exception here, and not wrapping it, but such a basic error condition not being caught seems unlikely to me.  Can anyone help me to find the root of this issue?
I'll include web.xml and servlet.xml too:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

servlet context:
<context:component-scan base-package="com.mycomp.proj.ws" />
    <bean id="smmService" class="com.mycomp.proj.ws.SMMRequestHandlingServiceStubImpl"/>

    <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"/>
    <bean class="org.springframework.ws.server.endpoint.adapter.MarshallingMethodEndpointAdapter">
        <constructor-arg ref="marshaller"/>
    </bean>
    <bean id="marshaller" class="org.springframework.oxm.castor.CastorMarshaller">
        <property name="mappingLocations">
            <list>
                <value>classpath:mapping.xml</value>
                <value>classpath:hoursOfOperationMapping.xml</value>
            </list>
        </property>
    </bean>

    <bean id="smmws" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
        <property name="schema" ref="schema" />
        <property name="portTypeName" value="SMM" />
        <property name="locationUri" value="/SMMWebServices/"/>
        <property name="targetNamespace" value="http://mycomp.proj.com" />
    </bean>

    <bean id="exceptionResolver" class="com.wdp.smm.ws.MyExceptionResolver"/>

    <bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
        <property name="xsd" value="/WEB-INF/ws.xsd" />
    </bean>

A: The MessageDispatcherServlet creates its own two instances of EnpointExceptionResolver by default, namely
SoapFaultAnnotationExceptionResolver@1
and
SimpleSoapExceptionResolver@2
And when it resolves an exception the SimpleSoapExceptionResolver@2 will stop any other registered EnpointExceptionResolver to handle an exception.
It took me embarrassingly long to figure out, but the answer is quite simple,
in your servlet context you have to do this:
<bean id="exceptionResolver" class="com.wdp.smm.ws.MyExceptionResolver">
    <property name="order" value="1"/>
</bean>

A: I've looked more closely at your question and I think that I know what's happening. You exception handler is not called because it is in the higher level in the soap processing. You see, WebServiceMessageReceiverHandlerAdapter tries to decode the incoming string to an XML before sending it to the marshaller to be processed. Since the XML is invalid the call fails. And since WebServiceMessageReceiverHandlerAdapter does not support an exception handler, it just rethrows the exception "SaajSoapMessageException".
Now what you can do is create a new class that extends WebServiceMessageReceiverHandlerAdapter, but that also wraps handleConnection() in a try/catch that uses your exception handler when a exception is throw.

By the way, when debugging this kind of problem my approach is to output both method name and line number in log4j. As well as downloading the Spring sources.

A: I think what @thierry-dimitri-roy explained is correct, however I had a lot of issues actually implementing it. For example, just wrapping the handleconnection method isn't enough due to noendpointfoundexception not being thrown. As this is more general issue of handling exceptions nicely, I'm putting my code here to ease the pain for future generations. This is tested with spring-ws 2.1.3 and JBoss AS7.
My message handler converts all problems to soap faults with response code 200.
package fi.eis.applications.spring.soap.server.transport.http;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ws.FaultAwareWebServiceMessage;
import org.springframework.ws.InvalidXmlException;
import org.springframework.ws.NoEndpointFoundException;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.context.DefaultMessageContext;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.support.DefaultStrategiesHelper;
import org.springframework.ws.transport.EndpointAwareWebServiceConnection;
import org.springframework.ws.transport.FaultAwareWebServiceConnection;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageReceiver;
import org.springframework.ws.transport.context.DefaultTransportContext;
import org.springframework.ws.transport.context.TransportContext;
import org.springframework.ws.transport.context.TransportContextHolder;
import org.springframework.ws.transport.http.HttpServletConnection;
import org.springframework.ws.transport.http.HttpTransportConstants;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter;
import org.springframework.ws.transport.support.TransportUtils;

/**
 * Adapter to map XML parsing and other low-level errors to SOAP faults instead of
 * server standard error pages. Also, this class will always use return code HTTP_OK
 * (status 200) to requests, even if there are errors.
 *
 */
public class MyWebServiceMessageReceiverHandlerAdapter
    extends WebServiceMessageReceiverHandlerAdapter
    implements HandlerAdapter, Ordered, InitializingBean, ApplicationContextAware {

    private ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        DefaultStrategiesHelper defaultStrategiesHelper = new DefaultStrategiesHelper(MessageDispatcherServlet.class);
        WebServiceMessageFactory factory = defaultStrategiesHelper
                .getDefaultStrategy(WebServiceMessageFactory.class, context);
        setMessageFactory(factory);
    }

    public ModelAndView handle(HttpServletRequest httpServletRequest,
                               HttpServletResponse httpServletResponse,
                               Object handler) throws Exception {
        if (HttpTransportConstants.METHOD_POST.equals(httpServletRequest.getMethod())) {
            WebServiceConnection connection = new MyWebServiceConnection(httpServletRequest, httpServletResponse);
            try {
                overriddenHandleConnection(connection, (WebServiceMessageReceiver) handler);
            } catch (InvalidXmlException ex) {
                handleInvalidXmlException(httpServletRequest, httpServletResponse, handler, ex);
            } catch (Exception ex) {
                handleGeneralException(httpServletRequest, httpServletResponse, handler, ex);
            }
        }
        else {
            handleNonPostMethod(httpServletRequest, httpServletResponse, handler);
        }
        return null;
    }

    /**
     * Overridden version of handleConnection from WebServiceMessageReceiverObjectSupport to be able to handle
     * missing endpoint ourselves. That method is final, so we need to use another method here.
     *
     * This has been reported as https://jira.springsource.org/browse/SWS-850
     *
     * @param connection
     * @param receiver
     * @throws Exception
     */
    protected void overriddenHandleConnection(WebServiceConnection connection, WebServiceMessageReceiver receiver)
            throws Exception {
        logUri(connection);
        TransportContext previousTransportContext = TransportContextHolder.getTransportContext();
        TransportContextHolder.setTransportContext(new DefaultTransportContext(connection));

        try {
            WebServiceMessage request = connection.receive(getMessageFactory());
            MessageContext messageContext = new DefaultMessageContext(request, getMessageFactory());
            receiver.receive(messageContext);
            if (messageContext.hasResponse()) {
                WebServiceMessage response = messageContext.getResponse();
                if (response instanceof FaultAwareWebServiceMessage &&
                        connection instanceof FaultAwareWebServiceConnection) {
                    FaultAwareWebServiceMessage faultResponse = (FaultAwareWebServiceMessage) response;
                    FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection;
                    faultConnection.setFault(faultResponse.hasFault());
                }
                connection.send(messageContext.getResponse());
            }
        }
        catch (NoEndpointFoundException ex) {
            if (connection instanceof EndpointAwareWebServiceConnection) {
                ((EndpointAwareWebServiceConnection) connection).endpointNotFound();
            }
            throw ex;
        }
        finally {
            TransportUtils.closeConnection(connection);
            TransportContextHolder.setTransportContext(previousTransportContext);
        }
    }

    private void logUri(WebServiceConnection connection) {
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("Accepting incoming [" + connection + "] at [" + connection.getUri() + "]");
            }
            catch (URISyntaxException e) {
                // ignore
            }
        }
    }

    private void handleGeneralException(
            HttpServletRequest httpServletRequest,
            HttpServletResponse response, Object handler,
            Exception ex) throws IOException {
        writeErrorResponseWithMessage(response, ex.getClass().getName() + ": " + ex.getMessage());
    }

    /**
     * By default, sets SC_BAD_REQUEST as response in Spring, so overwritten to
     * provide HTTP_OK and reasonable SOAP fault response.
     */
    protected void handleInvalidXmlException(
            HttpServletRequest httpServletRequest,
            HttpServletResponse response, Object handler, InvalidXmlException ex)
            throws IOException {
        writeErrorResponseWithMessage(response, ex.getClass().getName() + ": " + ex.getMessage());
    }

    /**
     * By default, sets SC_METHOD_NOT_ALLOWED as response in Spring, so overwritten to
     * provide HTTP_OK and reasonable SOAP fault response.
     */
    protected void handleNonPostMethod(HttpServletRequest httpServletRequest,
                                       HttpServletResponse response,
                                       Object handler) throws Exception {
        writeErrorResponseWithMessage(response, "HTTP Method not allowed");
    }

    private void writeErrorResponseWithMessage(HttpServletResponse response, String message)
            throws IOException {
        String errorXml = String.format(
                 "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                +"    <SOAP-ENV:Header/>"
                +"    <SOAP-ENV:Body>"
                +"        <SOAP-ENV:Fault>"
                +"            <faultcode>SOAP-ENV:Client</faultcode>"
                +"            <faultstring xml:lang=\"en\">%s</faultstring>"
                +"        </SOAP-ENV:Fault>"
                +"    </SOAP-ENV:Body>"
                +"</SOAP-ENV:Envelope>",
                StringEscapeUtils.escapeXml(message)
                );

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/xml");
        response.getWriter().write(errorXml);
        response.getWriter().flush();
    }
    @Override
    public int getOrder() {
        return 1;
    }

    /**
     * This class is needed as org.springframework.ws.transport.http.HttpServletConnection will throw an
     * exception if it is used outside Spring framework files. However, extending it and using the same
     * implementation seems to be fine.
     *
     */
    static class MyWebServiceConnection extends HttpServletConnection {
        protected MyWebServiceConnection(HttpServletRequest httpServletRequest,
                HttpServletResponse httpServletResponse) {
            super(httpServletRequest, httpServletResponse);
        }
    }
}

This needs to be also configured correctly. This is the thing that is needed on spring context:
<!-- 'messageReceiverHandlerAdapter' is a magic name spring-ws
     org.springframework.ws.transport.http.MessageDispatcherServlet
     will bind to -->
<bean id="messageReceiverHandlerAdapter"
    class="fi.eis.applications.spring.soap.server.transport.http.MyWebServiceMessageReceiverHandlerAdapter">
</bean>

A: The solution I could come up with is to override the doService method in the MessageDispatcherServlet and capture the exception, then render a custom response. This might not be the best solution for you, but it works for me, hope this helps!
public class CustomMessageDispatcherServlet extends MessageDispatcherServlet {

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        super.doService(request, response);
    } catch (Exception e) {
        String error = e.getMessage();
        String errorXml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                                "<SOAP-ENV:Header/>" +
                                    "<SOAP-ENV:Body>" +
                                        "<SOAP-ENV:Fault>" +
                                            "<faultcode>SOAP-ENV:Client</faultcode>" +
                                            "<faultstring xml:lang=\"en\"></faultstring>" + error +
                                        "</SOAP-ENV:Fault>" +
                                    "</SOAP-ENV:Body>" +
                                "</SOAP-ENV:Envelope>";
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/xml");
        response.getWriter().write(errorXml);
        response.getWriter().flush();
    }
}

}
You might want to catch only the exceptions you want to handle.
Replace org.springframework.ws.transport.http.MessageDispatcherServlet with your CustomMessageDispatcherServlet in the web.xml file.
<servlet>
    <servlet-name>web-services</servlet-name>
    <servlet-class>CustomMessageDispatcherServlet</servlet-class>
</servlet>

A: I remember running into this kind of problem when working with spring-security. I also had issues with my exception resolver not being invoked under some condititions.
The problem then was that there is a filter chain that handles each request. The code that invokes the exception resolvers is a filter in this chain, but it is close to the end of the chain. Hence, if an exception ocurred somewhere within the filters before the exception resolver invoking filter, my resolver would never be invoked.
I am guessing you suffer from something similar here, where envelope parse errors happen before the exception resolver invoking filter. If that is the case, you will have to resort to some other way of handling those exceptions, for example a vanilla servlet filter.

A: In the latest Spring WS version you can use custom webservice message listener
public class CustomWebServiceMessageListener extends WebServiceMessageListener {

private static final Logger LOG = LoggerFactory.getLogger(CustomWebServiceMessageListener.class);

@Override
public void onMessage(Message message, Session session) throws JMSException {
    try {
        this.handleMessage(message, session);
    } catch (JmsTransportException jmsTransportException) {
        LOG.error(jmsTransportException.getMessage(), jmsTransportException);
    } catch (Exception e) {
        JMSException jmsException = new JMSException(e.getMessage());
        jmsException.setLinkedException(e);
        LOG.error(e.getMessage(), e);
    }
  }
}

And inject it like this:
  <bean id="messageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="concurrentConsumers" value="#{properties.concurrentListeners}"/>

    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="destination" ref="queue"/>
    <property name="messageListener" ref="messageListener"/>
    <property name="sessionTransacted" value="true"/>

</bean>

<bean id="messageListener" class="com.yourproject.transport.CustomWebServiceMessageListener">
    <property name="messageFactory" ref="saajMessageFactory"/>
    <property name="messageReceiver" ref="messageDispatcher"/>
</bean>

A: Since the doService no longer throws an error for invalid XML and simply sets status to 400, I had to explore further on Chen's answer and implemented the following.
public class CustomWebServiceMessageReceiverHandlerAdapter extends WebServiceMessageReceiverHandlerAdapter {

  @Override
  protected void handleInvalidXmlException(HttpServletRequest httpServletRequest,
                                           HttpServletResponse httpServletResponse,
                                           Object handler,
                                           InvalidXmlException ex) throws IOException {
    String error = ex.getMessage();
    String errorXml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
        "<SOAP-ENV:Header/>" +
        "<SOAP-ENV:Body>" +
        "<SOAP-ENV:Fault>" +
        "<faultcode>SOAP-ENV:Client</faultcode>" +
        "<faultstring xml:lang=\"en\"></faultstring>" + error +
        "</SOAP-ENV:Fault>" +
        "</SOAP-ENV:Body>" +
        "</SOAP-ENV:Envelope>";
    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    httpServletResponse.setContentType("text/xml");
    httpServletResponse.getWriter().write(errorXml);
    httpServletResponse.getWriter().flush();
  }
}

On the bean configuration updated messageDispatcherServlet as below by setting messageReceiverHandlerAdapterBeanName to use the custom WebServiceMessageReceiverHandlerAdapter.
  @Bean
  public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
    MessageDispatcherServlet servlet = new MessageDispatcherServlet();
    servlet.setApplicationContext(applicationContext);
    servlet.setMessageReceiverHandlerAdapterBeanName("customMessageReceiverHandlerAdapter");
    return new ServletRegistrationBean(servlet, "/ws/*");
  }

  @Bean
  public CustomWebServiceMessageReceiverHandlerAdapter customMessageReceiverHandlerAdapter() {
    CustomWebServiceMessageReceiverHandlerAdapter customWebServiceMessageReceiverHandlerAdapter =
        new CustomWebServiceMessageReceiverHandlerAdapter();
    customWebServiceMessageReceiverHandlerAdapter.setMessageFactory(new DomPoxMessageFactory());
    return customWebServiceMessageReceiverHandlerAdapter;
  }

A: You have to "wire" (or "inject") the exception handler in your spring beans. I'm not sure which of your Spring bean actually needs the exception handler.
Personally, I use default-autowire="byName", which cause my exceptionHandler to be wired in my Controller class automatically. Your approach actually use manual wiring. So you need to find out which bean should actually use the exception handler. Have you tried (just on top of my head):
<bean class="org.springframework.ws.server.endpoint.adapter.MarshallingMethodEndpointAdapter">
    <constructor-arg ref="marshaller"/>
    <property name="exceptionHandler" ref="exceptionHandler" />
</bean>

Or you could just add the autowired mechanism of Spring and let it wire the beans automatically. :)


text:
Q: Pygame beginner programs, screen undefined AMOUNT = 1
x = 175
y = 175

def main():
    screen = pygame.display.set_mode((600,600))
    screen.fill( (251,251,251) )
    BoxAmountCalc(humaninput)
    DrawBoxCalc()
    pygame.display.flip()

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return

def BoxAmountCalc(x):
    x = (2**humaninput) * (2**humaninput)
    size = 600/x
    return size
def DrawBoxCalc():
    while True:
        pygame.draw.rect(screen,(0,0,0), (x,y,size,size))
        AMOUNT += 1
        x = x + size
        x = y + size
        pygame.display.flip()
        if AMOUNT > humaninput:
            break

I've left out a few parts of the code, some of the variable definitions, but when I try to run this code it gives me an error saying that "screen" is not defined.
Is this because I need it to be defined as a parameter for the function and then pass it into the function, or am I missing something completely here?
Thank you for looking, I'm sorry for a very beginner question.

A:
Is this because I need it to be defined as a parameter for the
  function and then pass it into the function.

Yes.  Once a function finishes executing, the variables created therein are destroyed.  Here is an example:
def go():
    x = 10

go()
print(x)

--output:--
Traceback (most recent call last):
  File "1.py", line 5, in <module>
    print(x)
NameError: name 'x' is not defined

Same thing here:
def go():
    x = 10

def stay():
    print(x)

go()
stay()

--output:--
 File "1.py", line 9, in <module>
    stay()
  File "1.py", line 6, in stay
    print(x)
NameError: name 'x' is not defined

But:
x = 10

def go():
    print(x)

go()

--output:--
10

And better:
def go(z):
    print(z)

x = 10
go(x)

--output:--
10

Try to keep your functions self contained, which means they should accept some input and produce some output without using variables outside the function.
In your code, you can do:
DrawBoxCalc(screen) and def DrawBoxCalc(screen):
but you also have an issue with humaninput.  I would try to define DrawBoxCalc as DrawBoxCalc(humaninput, screen), and call it with both args.  That means you will have to define main as main(humaninput).
Also, function names should start with a lower case letter, and python uses what is called snake_case for lower case names, so draw_box_calc, and class names should start with a capital letter and they can use camel case: class MyBox.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does cron run scheduled but missed script(because of sleeping) after wake up? I use fedora20 and its default cron. I have a cron job script that puts the server to sleep at 10:30am with rtcwake, and it wakes up at 12:30pm. If I run the script manually at 9:40am, it will also wake up at 12:30pm. If I run the script manually at 9:40am, will it run the missed cron task at 10:30am after wake up at 12:30pm and goes to sleep right away(which makes it wake up at 3:30pm)?
That seems to be what is happening with my server, and I want to know if the cron runs the missed job after wakeup.  If so, is there any way to change this behavior?  Thank you very  much.

A: Fedora defaults to chronie, which incorporates anacron-like functionality to run jobs periodically even when the system is off. The defaut /etc/anacrontab looks like this:
#period in days   delay in minutes   job-identifier   command
1       5       cron.daily              nice run-parts /etc/cron.daily
7       25      cron.weekly             nice run-parts /etc/cron.weekly
@monthly 45     cron.monthly            nice run-parts /etc/cron.monthly

... which means that by default any scripts you put into one of those directories (/etc/cron.[daily,weekly,monthly]) will run even if the computer is off. However, stuff in /etc/crontab or /etc/cron.d or user crontabs won't work that way. Look at man anacrontab for how to add new entries, if the existing periodic schedules don't work for you.

A: Not all cron daemons handle cases for noncontinuous uptime.  One which is specifically designed to run "missed" jobs is anacron.


text:
Q: Count the number of elements within a set of ranges I am facing trouble on writing a function that takes 2 arguments (values, dividers) as a list and returns the number of elements in each range (determined by numbers in dividers) as one list. Elements that are equal to one of the dividers should be counted in the bin below.
I used if and elif to sort the numbers, which is sort of giving me the right idea. However, I am struggling on how to apply the fact 'number of bins = number of dividers + 1'
def histogram(values, dividers):
    count1 = 0
    count2 = 0
    count3 = 0
    index = 0
    for index in range(len(values)):
        if values[index] <= min(dividers):
           count1 = count1 + 1
        elif min(dividers) < values[index] <= min(dividers):
           count2 = count2 + 1
        elif values[index] > max(dividers):
           count3 = count3 + 1
        index = index + 1
    print("Number of elements in each bin is ", [count1, count2, count3])

When I run the argument ([1,...,10], [2,5,7]) for instance, the answer should be [2,3,2,3] because the number of elements in range below 2, 2~5 (not including 5), 5~7 (not including 7) and above 7 is 2,3,2,3 respectively. However at the moment, I am getting the output [2,5,3].
P.S. My aim is writing the function without using numpy.histogram or any matplotlib related stuff

A: It's not the most efficient implementation, but it does not assume that values is sorted (only that dividers is):
def histogram(values, dividers):
    bins = [0]*(len(dividers)+1)
    extended_dividers = [-float('inf')]+dividers+[float('inf')]
    for idx, divider in enumerate(extended_dividers[:-1]):
        bins[idx] = len([v for v in values if divider<v<=extended_dividers[idx+1]])
    return bins

Also, shouldn't the output in your example be 1,2,3,4?


text:
Q: Distinct combination of value for a specific path I've a XML tree where each node has one child. As show here.
Is there a way to find the distinct combination of values related to a specific path?
For example if consider the tree in the previous example, I would like to find all the different combinations of tag based on their values:
INPUT: /A/C/D
<C value="1.7"><D value="0.4"></D></C>
<C value="1.4"><D value="0.2"></D></C>
<C value="1.4"><D value="0.4"></D></C>
<C value="1.4"><D value="0.2"></D></C>
<C value="1.5"><D value="0.2"></D></C>
<C value="1.5"><D value="0.1"></D></C>
<C value="1.5"><D value="0.2"></D></C>
<C value="1.4"><D value="0.3"></D></C>
<C value="1.4"><D value="0.2"></D></C>

INPUT: /C/D
<C value="1.4"><D value="0.2"></D></C>
<C value="1.4"><D value="0.3"></D></C>
<C value="1.4"><D value="0.4"></D></C>
<C value="1.5"><D value="0.1"></D></C>
<C value="1.5"><D value="0.2"></D></C>
<C value="1.7"><D value="0.4"></D></C>

A: You could try something like
distinct-values(
   A//C//D/string-join(
     ancestor-or-self::*[self::A|self::C|self::D]/@value, '|'))


text:
Q: How to pass controller parameters in Ruby on Rails When I write a message and when pressing the send option,
I want to store student_id, coach_id and message to the database. student_id and coach_id are being saved, but the message field is not being saved. It shows null in the database. How do I fix this?
Any help is appreciated.
Controller file:
class CourseQueriesController <ApplicationController
  def index
    @course_query = CourseQuery.new
  end

  def create
    # @course_query = CourseQuery.new(course_query_params)
    @course_query = CourseQuery.where(student_id: current_student.id, coach_id: "2", message: params[:message]).first_or_create
    if @course_query.save
      redirect_to course_queries_path, notice: 'Query was successfully send.'
    else
      render :new
    end
  end

  private

  def set_course_query
    @course_query = CourseQuery.find(params[:id])
  end

  # def course_query_params
  #   params[:course_query].permit(:message)
  # end
end

model/course_query.rb:
class CourseQuery < ActiveRecord::Base
  belongs_to :student
  belongs_to :coach
end

view/course_query/index.html.erb:
<%= simple_form_for (@course_query) do |f| %>
<%= f.button :submit , "Send or press enter"%>
<%= f.input :message %>
<% end %>

database /course_queries:

A: It seems you didn't permit :course_query.
Try to permit your params the following way:
 def course_query_params
   params.require(:course_query).permit(:message)
 end

But according to the 2nd way you pass params (params[:message]) I think you have a bit different params structure. So try another one:
 def course_query_params
   params.permit(:message)
 end

A: When you look into the params generated in the log, you will see that the message inside the course_query hash, so params[:message] should be params[:course_query][:message]
@course_query = CourseQuery.where(student_id: current_student.id, coach_id: "2", message: params[:course_query][:message]).first_or_create


text:
Q: Sliding divs in and out of page view simutaniously Im fairly new to javascript. Ive adapted some script Ive found to do something similar to what I need but its not working as I'd like it too. I apologize for the long explanation.
I have 6 buttons, button 1 -3 responsible for the left divs, and button 4 - 6 responsible for the divs on the right.
When the script run, none of the divs should be visible.
When buttons#1 is clicked, div#1 slides out from the left and is then positioned its own width from the left of the container. This is the same for div#2 and div#3 corresponding to button#2 and button#3. Only 1 div can be seen at a time so button#2 will hide div#1 and div#3 and show div#2, ect. Same for all the other buttons.
When button#4  is clicked, div#4 slides out from the right and is positioned its own width from the right of the container. The hiding of the divs when another button is clicked is the same as the above, only 1 div can be seen at a time.
Help would greatly be appreciated.

Click Box #1

Click Box #2

Click Box #3

Click Box #4

Click Box #5

Click Box #6

Box #1

Box #2

Box #3

Box #4

Box #5

Box #6

A: jsfiddle.net/KFqvf
This is a jsfiddle with what I think you want in. Just needs simple jquery animate function to slide in left and right, and a simple menu to select the items!
Hope this helps


text:
Q: Dispatch is not saving data in datalayer in React Context Api I'm following a tutorial where they are making a clone of Spotify. For that I got the user access token to access all the user data. And to avoid prop-drilling I'm using React Context-api to save and pull user data (token, user info, playlist info, etc.). In my Sidebar.js I'm want to pull playlist info from the datalayer context and show it to the user. But the playlist info isn't showing there and after console logging, I got undefined. To be sure, I also console logged the playlist info in App.js, there I'm getting all the information I need but not in the Sidebar.js. I've attached the screenshot of what I'm getting in this link --> https://ibb.co/PGj4XcT ,
Any help would be appreciated.
Sidebar.js
function SideBar() {
  const [{ playlists }, dispatch] = UseDataLayerValue();
  console.log("user playlist from sidebar.js", playlists);

  return (

      <SidebarOption Icon={HomeIcon} title="Home" />
      <SidebarOption Icon={SearchIcon} title="Search" />
      <SidebarOption Icon={LibraryMusicIcon} title="Your Library" />

      PLAYLISTS

      {playlists?.items?.map((list) => {
        return <SidebarOption title={list.name} />;
      })}

  );
}

App.js
function App() {
  const [{ token }, dispatch] = UseDataLayerValue();

  useEffect(() => {
    const hash = getTokenFromUrl;
    window.location.hash = "";
    const _token = hash.access_token;

    if (_token) {
      dispatch({
        type: "SET_TOKEN",
        token: _token,
      });
      // setToken(_token);

      spotify.setAccessToken(_token);

      spotify.getMe().then((user) => {
        dispatch({
          type: "SET_USER",
          user: user,
        });
      });

      spotify.getUserPlaylists().then((playlist) => {
        console.log("user playlist from app.js", playlist);
        dispatch({
          type: "SET_PLAYLIST",
          playlists: playlist,
        });
      });
    }
  }, [dispatch]);

  //console.log(user);
  //console.log(token);
  return (

      {token ? <Player spotify={spotify} /> : <Login />}

  );
}

Reducer.js
export const initialState = {
  user: null,
  playlists: [],
  playing: false,
  item: null,
  token: null,
};

export const reducer = (state, action) => {
  switch (action.type) {
    case "SET_USER":
      return {
        ...state,
        user: action.user,
      };
    case "SET_TOKEN":
      return {
        ...state,
        token: action.token,
      };
    case "SET_PLAYLIST":
      return {
        ...state,
        playlists: action.playlist,
      };
    default:
      return state;
  }
};

A: All I had to do is add return before <SidebarOption title={list.name} />; .. As I'm using curly braces that's why I forgot to add return, At first I thought the arrow function automatically returns something but I was wrong. As I was using {} so I had to add return in front of the statement. I've updated the Sidebar.js


text:
Q: issue with search form im developping a plugin that have a custom search page for a custom post, i have create my custom page like this
<?php

/*
Template Name: search-sa_notification
*/?>

<?php get_header(); ?>

            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

                <input class="form-control" type="text" placeholder="something" name="cernmb" />

                <input class="button small yellow" type="submit" value="search" name="submit" />
                <input class="button small yellow" type="hidden" value="test" name="sbtn" />
            </form>

<?php
    if(isset($_POST['submit']) and $_POST['sbtn']=='test'){
        echo "ur number is ".$_POST['cernmb']."\n";
    }
?>
<?php get_footer(); ?>

the problem im facing is that when i click on search i got redircted to index page while me i wanna stay in this search page and display the msg in test condition but i got redircted to index page instead

A: It seems like this line is your problem:
<?php echo $_SERVER['PHP_SELF']; ?>

When I put that in different template files on a WordPress site, it always echo's out the path to the index.php. Try making that the path to the template file instead.
If you want the form to be submitted back to the same page, just leave the action attr blank:
<form method="post" action="">


text:
Q: How to manage developing former Visual Studio solution in Linux? sigh
In my third try to introducing Linux to my everyday life I'm still bouncing hard on programming.
I have solution for my major thesis' program created in Visual Studio (five projects in one solution; 4 static libs, one executable), and managed with it since it's beginning. It's posted on Git, so I thought, that I'll try changing it and compiling on my laptop with Ubuntu 18.4. While changing it was no-effort task (Linux text editors are neat; as opposed to almost non-existent IDEs), compiling in the other hand was the point I doubted in all my skills.
First problem I've encountered is that I have no idea how to manage multiple projects outside VS. I mean, there are .vcxproj files with data, but not very useful for what I saw.
Second problem are references - I have no idea how to link #include directories to specific point in files without going ../MainFolder/subfolder/file.h which is extremely unesthetic.
I expect, that those are just iceberg's peaks, and I will encounter massive amount of problems in future, but as for now - can anybody give me idea of how to manage such project in Linux?


text:
Q: iphone (or ipad mini) as a helmet mounted display I like to watch educational videos from coursera on my iphone or ipad mini while I walk.
I was thinking of making a helmet mounted mount where I could essentially do without holding the ipad in my hand - perhaps using a bicycle helmet as a starting point.
Question: Do you know of something like this that already exists?
Note: The TregoBag will not fit my requirements I think.
Thanks.


text:
Q: Novel with powdered sugar explosion Looking for a novel published in the '80s or '90s.
Contains the following elements:
Most memorable scene - people are eating beignets in a cafe. They blow powdered sugar off the tops of the beignets and the resulting sugar cloud accidently ignites, blowing up the cafe.
Action takes place on spaceships and on at least one planet, possibly called 'Beau Soleil'
There are sentient starships.
There is some sort of drug that heightens your artistic/aesthetic sense. One group also uses it for mind to mind interface with their sentient ships.

A: Gonna go with Blind Justice, published in 1991 by S.N. Lewitt.

From a review in the Dragon Magazine (large PDF, page 35):

Enter the Mary Damned, first Syndicat starship chosen to take this
  defiance into the open, and enter Emile Saint-Just, its newest
  crewmember. Saint-Just is the last survivor when the Mary Damned's
  crew is captured by the Justica, and as the ship vanishes into legend,
  he becomes the key to finding the lost spacecraft and bringing the
  legend back to life. After a term on a Justica prison ship, Emile
  returns home to the colony world of Beau Soleil - also the target of a
  Justica takeover and becomes involved with a volatile team of
  underground resistors.

Someone else on Reddit was looking for the same book, and mentioned the "Mary Celeste" (most likely a mis-remembering of the Mary Damned).


text:
Q: No such file or directory /etc/init.d/functions I created a startup script to start/restart/stop a group of applications. I used the lib /etc/init.d/functions in my script. It is working well on my system, but it not working for my client; he is getting the error:

No such file or directory /etc/init.d/functions

Right now I don't know which linux distro my client uses. Is the init.d/functions file different for different Linux distros? If so, how can I find it?

A: It's specific to whatever distribution you're running.  Debian and Ubuntu have /lib/lsb/init-functions; SuSE has /etc/rc.status; none of them are compatible with the others.  In fact, some distributions don't use /etc/init.d at all, or use it in an incompatible way (Slackware and Arch occur to me off the top of my head; there are others).

A: In CentOS 7 Docker image I had to simply install the package initscripts in order for this script to be installed:
yum install -y initscripts

(Thanks to this issue on docker-library which made me look at this commit)

A: Adding a recent answer
As noted in another answer, Linux Standard Base (LSB) specs provide a way to write platform independent init.d based startup scripts, using the LSB defined init functions as listed here
All LSB compliant distributions (all the big ones) provide the file /lib/lsb/init-functions (which defines the listed functions) in the meta-package lsb-core-noarch which can be installed using the distribution's package manager $PKGMAN $INSTOPT lsb-core-noarch (yum,dnf,apt,...).
An example of such an init script is this.
However, given how systemd is now the de-facto system and service manager for most distributions, it's better to write a systemd service unit instead of writing out an initscript.

A: That is absolutely distribution dependent. You're really going to need to find out the distro in order to write a properly-matching init script.
You can also follow the LSB (Linux Standard Base) specification and hope that the distro in question did too. The current specification dictates that the standard init script functions be available as /lib/lsb/init-functions (see docs here). On Fedora and other Red Hat related distros, that's provided by the redhat-lsb package, which is optional.
So, you really have to figure out what you're targeting. Sorry.

A: I missed those functions when I moved to Ubuntu, so I created a library that recreates their functionality: efunctions.

A: I too got the same error while I run my docker container. It was fixed by adding below line in my Dockerfile
RUN yum install -y initscripts


text:
Q: JPype conflicts with django and raven I am using jpype 0.6.1. I have written a python script to run some piece of code written in scala. Every thing is working as expected. But when I have integrated python script into my django project, I was getting some errors related to raven module.
Scala code to print message :
package com.test.auth

object Auth {
  // returns the message passed as parameter
  def printMessage(message: String) : String = {
    message
  }
}

Python script that accesses above code
import jpype
from jpype import *

classpath = '-Djava.class.path=/home/ec2-user/dt/jars/Auth.jar'

jpype.startJVM(jpype.getDefaultJVMPath(),classpath)
authPackage = JPackage('com.test.auth')
Auth = authPackage.Auth
msg = Auth.printMessage("Hello World")
print "message : ",msg

The above code is working fine. but after integrating into django project, I was getting following error

TypeError: Package com.test.auth.Auth.printMessage.__sentry__ is not
  Callable 2016-08-16 07:56:08,850 [ERROR]
  logger=sentry.errors.serializer process=14605 thread=140040558467072
  Package com.test.auth.Auth.printMessage.__sentry__ is not Callable

I am new to django. I have read about the raven logging mechanism. but unable to find the issue.

A: Looking into this, we're just logging this and this should not interfere with Raven's normal reporting.

A: I had just the same problem. I manage fix this after putting on the Django project root folder the folder with all .class files that i was using.


text:
Q: separate key-value pairs of dict with semi-colon I am attempting to separate a dictionary with key-value pairs into a string that would look like the following:
'key1=value1;key2=value2; ...'

For example,
 data = {
    "amount": "12185",
    "job": "GAPA",
    "month": "JANUARY",
    "year": "2010"
  }

 console.log(Object.entries(cookies).map((keys, values) =>{console.log(`${keys}=${values}`)}).join(';'));
  console.log(Object.keys(cookies).map((keys, values) =>`${keys}=${values}`).join(';'));

Neither produce the expected output:
'amount=12185;job=GAPA;month=JANUARY;year=2010'

A:

data = {
    "amount": "12185",
    "job": "GAPA",
    "month": "JANUARY",
    "year": "2010"
};

const output = Object.entries(data).map(([key, value]) => `${key}=${value}`).join(';');
console.log(output);

A: using a reducer:

const data = {
  "amount": "12185",
  "job": "GAPA",
  "month": "JANUARY",
  "year": "2010"
};

const string = Object.entries(data)
  .reduce((currentStr, [key, value]) => currentStr + `${key}=${value};`, "");

console.log(string);

A: You can also go with your second approach
data = {
    "amount": "12185",
    "job": "GAPA",
    "month": "JANUARY",
    "year": "2010"
}
console.log(Object.keys(data).map((keys, index) =>`${keys}=${data[keys]}`).join(';'))

The problem is you've used the method .map() in the wrong way, it's supposed to be (key, index), the second argument is the index not value, but in your case, you won't need it anyway
Please have a look at the syntax here for more details

A:

const data = {"amount":"12185","job":"GAPA","month": "JANUARY","year":"2010"}

const r = Object.entries(data).map(x=>x.join('=')).join(';')

console.log(r)


text:
Q: Google apps script for Spreadsheet - russian symbol substitute as a question mark If you open a link in brazuere __ - that everything is OK, an entry is added in Russian.
If the same link run from php script - it added a question mark.
Here's the code dlyastranitsy pgoogl appps
 function doGet(e) {
  var ss = SpreadsheetApp.openById("14EWkOKE4QONFQ7UAi5Kf1vYnTgSXzCH_ZJZ5fzo3dIU");
  var ss = ss.getSheetByName('Лист');
  var rr=getFirstEmptyRowWholeRow(ss);
  ss.insertRowAfter(rr);
  Logger.log(e.parameter.tovar);
  ss.getRange('A'+rr).setValue(e.parameter.tovar);
}
function getFirstEmptyRowWholeRow(ss) {
  var values = ss.getDataRange().getValues();
  var row = 0;
  for (var row=0; row<values.length; row++) {
    if (!values[row].join("")) break;
  }
  return (row+1);
}

Here is the code php file
function obrab_url($s){
    return str_replace(' ','%20',nl2br($s));
}

$tovar='Коврики в сало н для тойоты колродлла аповдыало xcz lkjxzc ждмлчсяо8 987908';
$phone='09873569734';
$address='киев у богакая 8 выалвыоад лдож';
$cena='352 555';
$postavshik='[колч код 535] плюс [родлордло]';
$s='https://script.google.com/macros/s/AKfycbxGvknF1mMX6YCq8KZLltuWqJZ0QfthgGHnwOR11xaSPXQ91Ozb/exec?tovar='.obrab_url($tovar).'&phone='.obrab_url($phone).'&adres='.obrab_url($address).'&price='.obrab_url($cena).'&code='.obrab_url($postavshik);
echo $s.'<br>';

  $ch = curl_init();
  // GET запрос указывается в строке URL
  curl_setopt($ch, CURLOPT_URL, $s);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.1) Gecko/2008070208');
  $data = curl_exec($ch);
  curl_close($ch);
  echo $zap;


text:
Q: Oracle XMLTable / XMLTYPE (no idea) im trying to create DataBase using OracleXE11 and what im tring to do is create XML tables and input data into them.
Step 1:
CREATE TABLE Customer(
  customerId int Primary KEY,
  signUpDate Date NOT NULL,
  CustomerData XMLTYPE,
  CustomerAdress XMLTYPE);

Step 2:
CustomerData.xml
<?xml version="1.0"?>
<CustomerData>
    <Customer>
        <name>Alex Smith</name>
        <type>Fleet</type>
        <nip>1234567890</nip>
    </Customer>
    <Customer>
        <name>Saly North</name>
        <type>person</type>
        <nip>2345678901</nip>
    </Customer>
<CustomerData>

CustomerAdress.xml
<?xml version="1.0"?>
<CustomerAdress>
    <Adress>
        <city>Xxxx</city>
        <street>Yyyy 2</Street>
        <postcode>56-200</postcode>
    </Adress>
    <Adress>
        <city>Zzzz</city>
        <Street>Uuuu 5</street>
        <postcode>57-300</postcode>
    </Adress>
<CustomerAdress>

Step 3:
CREATE OR REPLACE DIRECTORY XMLDIR AS 'C:\xml_files';

Step 4:
Now i have a problem because i don't know how to input those data.
I've tried to:
INSERT INTO Customer (customerId, signUpDate, CustomerData, CustomerAdress) VALUES
(1, to_date('12-05-1970','dd-mm-yyyy'), XMLType(bfilename('XMLDIR', 'CustomerData.xml'), nls_charset_id('AL32UTF8')), XMLType(bfilename('XMLDIR', 'CustomerAdress.xml'), nls_charset_id('AL32UTF8')));

but it returns me 1 row (i know why... because in creating only 1 row using all xml files i've declared)
I wondered... maybe a PROCEDURE (PL/SQL) will help me with it
And another problems are (i need to use them all for update/insert/delete):
 - Xpath
 - DOM
 - SAX
 - Xquery
 - creating XML Schema to validate inputed XML File
 - write XML file from DB to file.xml on Desktop
 - read XML file.xml from Desktop to DB
Im not even sure if im started well with it.
//------------------------------------------------------------//
Im trying to insert xmlfile into table but i dont know how to separate data form xmlfile
what im expecting
ROW 1:
customerId = 1 ||
signUpDate = 12-05-1970 ||
CustomerData = <name>Alex Smith</name> <type>Fleet</type> <nip>1234567890</nip> ||
CustomerAdress = <city>Xxxx</city> <street>Yyyy 2</Street> <postcode>56-200</postcode>

ROW 2:
customerId = 2 ||
signUpDate = 26-10-2007 ||
CustomerData = <name>Saly North</name> <type>Person</type> <nip>2345678901</nip> ||
CustomerAdress = <city>Zzzz</city> <street>Uuuu 5</Street> <postcode>57-300</postcode>

.
.
.
ROW n:
customerId = n ||
signUpDate = dd-mm-yyy ||
CustomerData = <name>Xxx Yyy</name> <type>Xxx</type> <nip>nnnnnnnnnn</nip> ||
CustomerAdress = <city>Xxx</city> <street>Xxx</Street> <postcode>xx-xxx</postcode>

in my opinion thats how XMLTYPE table should looks like but i may be wrong (also i need to operate on this XMLDB using simply operations like insert/delete/update using sql query)

A: I think you are looking for XMLTable function, it is very useful, if you need to parse xml files.
You can load xml into another table, for example customer_xml and then use XMLTable function to parse xml data and insert into main table customer. For example:
CREATE TABLE CUSTOMER (customerid NUMBER,
                       signupdate DATE,
                       name VARCHAR2(255),
                       type VARCHAR2(255),
                       nip  VARCHAR2(255))
/
CREATE TABLE CUSTOMER_XML (dataxml XMLTYPE)
/
CREATE SEQUENCE seq_customer_id START WITH 1 INCREMENT BY 1
/
CREATE PROCEDURE p_customer_insert
IS
TYPE t_customer_aat IS TABLE OF customer%ROWTYPE INDEX BY PLS_INTEGER;
l_customer_aat t_customer_aat;
l_dataxml XMLTYPE;
BEGIN
    SELECT dataxml INTO l_dataxml
    FROM customer_xml;

    SELECT seq_customer_id.NEXTVAL, sysdate, x.*
    BULK COLLECT INTO l_customer_aat
    FROM XMLTABLE('/CustomerData/Customer' PASSING l_dataxml
                                           COLUMNS
                                           name VARCHAR2(255) PATH 'name',
                                           type VARCHAR2(255) PATH 'type',
                                           nip  VARCHAR2(255) PATH 'nip') x;

     FORALL indx in 1..l_customer_aat.COUNT
         INSERT INTO customer VALUES l_customer_aat(indx);
     COMMIT;
END;


text:
Q: Gaseous fission: Has it even been demonstrated experimentally? I've been reading quite a bit about gas-core reactors, a theoretical reactor design where the fissioning of Uranium(along with Plutonium & possibly Thorium)occurs in gas phase. The result is that the heat of the reaction converts the gaseous nuclear fuel into plasma which can be contained in a magnetic bottle. The most feasible design for such a reactor is cylindrical metal reactor vessel with a magnetic solenoid where the electromagnets push inward radially; confining the plasma. I would imagine that such a reactor would need an inner lining of neutron reflecting material to deflect neutrons and bounce them back and forth across the chamber. But do to the chemical properties of Uranium Hexafluoride gas it might be more prudent to use a single, supercritical solid fuel rod assembled vertically inside of a vacuum solenoid. The fuel rod would then be bombarded by intense microwaves from directly above to convert it into plasma after the electromagnets are turned on. But the question remains if it is even possible to compress the plasma to a high enough density to initiate fission. Has this experiment ever been tried? If so, what were the results?

A: Yes, there were experiments both in USA and USSR, but as far as I know all actual criticality experiments used only 'cold' UF$_6$ gas, not plasma ( not venturing even close to thousand degrees K so no MHD stuff / first wall thermal load testing was done).
Let me present a report  'Spherical Gas Core Reactor Critical Experiment' that was conducted at ~1969-1971 with NASA sponsorship at National Reactor Testing Station in Idaho.
From report:

During the latter half of 1969 a spherical geometry Cavity Reactor Mockup
  was constructed and nuclear testing with a highly enriched $^{235}\mathrm{UF}_6$ core commenced.

Summary of results:

The experiments were relatively "clean" and should serve as benchmarks for
  calculational purposes. The inner spherical gaseous fuel region (127 cm dia)
  was located in a 183 cm diameter cavity surrounded by 91 cm of commercial
  grade heavy water. The critical mass was 8.4 kg of uranium in gaseous UF$_6$ form.
  The second configuration had hydrogen added between the fuel and the cavity wall.
  The third added structural material to the cavity wall. The critical mass increased
  to 12.86 kg and 29.2 kg of uranium, respectively. Four methods of controlling
  reactivity were examined.

Obviously, by varying wall moderator/reflector material, mixing in moderator (CF, He) in the gas phase the critical mass could be reduced somewhat, lowering enrichment degree will increase critical mass, but at least this should give an idea.
Raising temperature while keeping density constant should keep critical mass more or less constant (the effects of neutron thermalization at different T shouldn't change it much), but of course it will greatly increase the pressure.
So yes, from the neutronics point of view there is no obstacles for this type of reactor, and all comes down to confining hot gas / plasma and keeping it from melting containment vessel.
As for the magnetic confinement of such plasma I would like to note that at pressures around 100 bar and temperatures around 5000 K the degree of ionization of UF$_x$ gas is far from 100 %. For instance the paper 'Use of thermochemical modelling for the analysis of energy extraction in a gas-core fission reactor' lists 6% for 7000 K @ 100 bar. This means that magnetically confined plasma would 'leak' neutral molecules which would still inflict pressure on/ exchange heat with the containment vessel.


text:
Q: Join table in Entity framework I'll have this query in joining the table but it did not returned data from Include table or Join table.
var tasks = (from item in ctx.Tasks
             join tp in ctx.TaskPlugins
             on item.TaskId equals tp.TaskId
             select item)
              .Include(x => x.TaskPlugins).Include(x => x.TaskPlugins.Select(p => p.Plugin)).Include(x=>x.TaskPlugins.Select(p=>p.Plugin.Store));
return ctx.Tasks.ToList();

But this query does not return data from TaskPlugins

Error Message: ((System.Data.Entity.DynamicProxies.Task_6F777A6C52D9E84FD3DF53481564A61969CE62ABBA9D985448F99BFB8A49A2D7)new System.Collections.Generic.Mscorlib_CollectionDebugView<oRouter.Model.Task>(task).Items[0]).TaskPlugins
Thanks.

A: One thing, You should be returning tasks.ToList() and not ctx.Tasks.ToList()
Second, the last include .Include(x=>x.TaskPlugins.Select(p=>p.Plugin.Store) is the only one needed. First 2 includes are NOT needed.


text:
Q: Regarding footer issue in pdf file creation using php and fpdf library
*

*I have created and successfully created my pdf file in php with fpdf
library support.

*But the problem is my footer is showing more space.

*I want to reduce the space underneath my text. My output is like
this:

Here my code goes:
<?php
    require('fpdf/fpdf.php');
    class PDF extends FPDF {

                function Header() {
                            $this->SetY(0.208333);
                        }
                function Footer() {
                                 if ($this->footer <> 1)
                                 {
                                $this->SetY(-15);
                             }
                             else
                             {
                                echo "bye";
                             }
                        }
    }

                        //class instantiation
                        $pdf=new PDF("l","in",array(8.5,4.17));
                            $pdf->SetFont('Arial','',8);
                            $pdf->footer = -15;
                            //Array2
                            $datas = array
                                    (
                                    'Address1' => array
                                    (
                                    'Name' => 'Vijaya',
                                    'Area' => 'Valasaravakkam',
                                    'City' => 'Chennai',
                                    ),
                                    'Address2' => array
                                    (
                                    'Companyname' => 'Vy Systems',
                                    'Area' => 'Valasaravakkam',
                                    'City' => 'Chennai',
                                    ),
                                    'Address3' => array
                                    (
                                    'Companyname' => 'Vy Systems1',
                                    'Area' => 'Valasaravakkam1',
                                    'City' => 'Chennai1',
                                    ),
                                    );
                            //Array2
                            $datas1 = array
                                    (
                                    'Address4' => array
                                    (
                                    'Name' => 'Jaya',
                                    'Area' => 'Valasaravakkam',
                                    'City' => 'Chennai',
                                    ),
                                    );

                            foreach($datas1 as $address1 => $details1)
                            {
                                //pdf_set_text_pos($pdf, 1240, 490);
                                //$pdf->ln(1);

                                    foreach($datas as $address => $details)
                                    {
                                        $pdf->SetMargins(0,0,0.3);
                                        $pdf->AddPage();
                                        if((is_array($details)) and (is_array($details1)))
                                        {
                                            foreach($details1 as $rows1 => $value1)
                                            {
                                                $pdf->SetX(0.520833);
                                                $pdf->MultiCell(0, 0.2, $value1, 0, "L");
                                            }
                                            $pdf->ln(1.96);
                                            foreach($details as $rows => $value)
                                            {
                                                $pdf->SetX(5);
                                                $pdf->MultiCell(5, 0.2, $value, 0, "L");
                                            }
                                        }

                                    }//end of sub foreach
                            }//end of main foreach

                        $pdf->Output();
?>

A: I didn't follow the code completely, but it seems you're using the Header and Footer methods to set Y and nothing more, expecting that to be enough to correctly position the MultiCells being output outside of the Header and Footer. Maybe so, but the interaction of positioning inside and outside the Header/Footer isn't well defined.
For example, the process may be something like this: Y is calculated for the MultiCell, that trips the footer, the footer changes Y, the MultiCell is output. Is this the original Y, the revised (by the footer Y), or some other value? Absent a precise definition of what happens, you've set up a complex sequence of things that would be very difficult to sort out.
I would suggest vastly simplifying the code. You may find that the automatic header/footer tripping isn't helpful at all. In that case, turn off the auto page break, get rid of the Footer/Header functions, and totally control each page yourself. That way at least you have a clear, reliable model of what's going on.


text:
Q: Как установить скидки и лимиты закупок? Мне нужно установить цены на услуги на платформе Magento.
Есть ряд условий: например, человек должен выбрать количество товаров, в зависимости от этой цифры будет рассчитан процент скидки; кроме того, есть ограничение на количество выбранных товаров, - если больше двухсот, то пользователь должен увидеть сообщение на экране "Contact us".
Я так понимаю, платформа имеет стандартные методы установки цены. Как их можно изменить? Или указанное возможно реализовать стандартными средствами Magento?

A: Про скидки: в Magento есть такая функция, как tier price. Выставляется количество, свыше которого цена изменяется, можно выставить несколько пороговых значений. На странице товара в админке во вкладке находится цена.
По поводу максимального количества: посмотри в system->config->checkout, там что-то вроде min cart qty / max cart qty. Min cart qty там точно есть. Может быть, и максимум. Сообщение «свяжитесь с нами» при достижении максимума можно доставить в шаблоне /app/design/твоя_тема/template/catalog/product/add_to_cart.phtml.


text:
Q: Google API Autentication - redirect_uri_mismatch error I'm trying to authenticate my web app with Google Plus API. In the Google Developer console under Credentials for my Cliend Id for Web Application.
I add the following redirect uri: http://localhost:50883/oauth/add_oauth_token
When I run my application I get the following Error:
400. That's an error.

Error: redirect_uri_mismatch

Application: SID3

You can email the developer of this application at: carlosmoralesdiego@gmail.com

The redirect URI in the request: http://localhost:55404/authorize/ did not match a registered   redirect URI.

Learn more

Request Details
from_login=1
response_type=code
scope=https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email    https://www.googleapis.com/auth/userinfo.profile
access_type=offline
redirect_uri=http://localhost:55404/authorize/
as=-45fed094242eac62
pli=1
client_id=389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv.apps.googleusercontent.com
authuser=0
hl=es

So for any reason google changes my redirect uri to the port 55404, why?. Thanks so much and regards
This is the code:
protected void LoginToGooglePlus(object sender, ImageClickEventArgs e)
    {

        PlusService service = null;
        UserCredential credential = null;

            string[] scopes = new string[] {PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail,
 PlusService.Scope.UserinfoProfile};
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
           try
        {
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            UserCredential credentials;
            using (var stream = new FileStream("C:\\Users\\Usuario\\Documents\\Visual Studio 2010\\Projects\\WebApplication1\\WebApplication1\\client_secret.json", FileMode.Open, FileAccess.Read))
            {

                credentials= GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("WebApplication1")).Result;
            }
        }
        catch (Exception ex)
        {
            //If the user hits cancel you wont get access.
            if (ex.InnerException.Message.IndexOf("access_denied") != -1)
            {
                Console.WriteLine("User declined access");
                Console.ReadLine();
                return;
            }
            else
            {
                Console.WriteLine("Unknown Authentication Error:" + ex.Message);
                Console.ReadLine();
                return;
            }
        }

        // Now we create a Google service. All of our requests will be run though this.
        service = new PlusService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "SID3",
        });

}

The json file which I use it's this one:
{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"jpkVDaaMjlLCHGh67DJ9Zv19","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":"389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv@developer.gserviceaccount.com","redirect_uris":["http://localhost:50880/Paneles.aspx"],"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv@developer.gserviceaccount.com","client_id":"389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv.apps.googleusercontent.com","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"}}

A: I just solved the same problem simply by changing DataStore to null.
credentials= GoogleWebAuthorizationBroker.AuthorizeAsync(
    GoogleClientSecrets.Load(stream).Secrets,
    scopes,
    Environment.UserName,
    CancellationToken.None,
    null // <-- here
    ).Result;

I don't know why but it stops the random port shenanigans.
I should also add, that in my case, it just solved one problem since I needed to publish my app online, where this solution was just wrong. If anyone needs the online version (asp.net 4.5 MVC 5) you can use the code here.

A: API redirect URL and your application Redirect URL Should be same....
For example (if your application URL Like this localhost:55404/authorize/ and need to add same URL in API Redirect URL localhost:55404/authorize/ )


text:
Q: WinForms C# - Proper method to free draw? I'm attempting to re-create something similar to Microsoft's Paint application. I'm using the Bitmap technique to render my drawings in order to have them be persistent. At 4 pixels x 4 pixels, it's unnoticeable, but as you go higher in the width, it's extremely noticeable, especially when you curve. I have a picture to show you what it looks like and some snippet.

        private void Form1_Load(object sender, EventArgs e)
    {
        //Initializing Graphics and Bitmap
        pnlMain.BackgroundImage = new Bitmap(pnlMain.Width, pnlMain.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        Doodle = Graphics.FromImage(pnlMain.BackgroundImage);
        Doodle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        Doodle.Clear(Color.White);
     }

private void pnlMain_MouseDown(object sender, MouseEventArgs e)
    {
        start = e.Location;
        if (cboDrawType.SelectedIndex == 0)
        {
        Painting = true;
        }

        private void pnlMain_MouseUp(object sender, MouseEventArgs e)
    {
        Painting = false;
    }

        private void pnlMain_MouseMove(object sender, MouseEventArgs e)
    {
      if (Painting == true && cboDrawType.SelectedIndex == 0)
        {
            end = e.Location;
            Doodle.DrawLine(ChosenPen, start, end);
            pnlMain.Refresh();
        }
      start = end;
    }

        private void nudSize_ValueChanged(object sender, EventArgs e)
    {
        ChosenPen.Width = Convert.ToUInt16(nudSize.Value);
    }

NOTE: start and end are new Point() variable members.
Sorry if the code is a bit messy, I had to cut it out brutally.
I'm using a pen even though it says Brush in the picture.
Doodle is my declared graphics

A: You should specify the StartCap and EndCap properties:
pen.StartCap = System.Drawing.Drawing2D.LineCap.Round;
pen.EndCap = System.Drawing.Drawing2D.LineCap.Round;

The default is Flat, which turns short lines with a high pen width into silly stripes.


text:
Q: django: how to evaluate a project for refactoring Has anyone of you done evaluation of a django project and how to improve/refactor it's code base? A pet project in company I work at is becoming more widely used and it would be good to improve its quality before further development. Are there any techniques or methodologies of analyzing django projects before we start putting more and more features into it? We wouldn't like to suddenly realise, that due to earlier poor choice we have to live with something really bad.

A: What I noticed after working more than a year on a quite large site was mostly this concerning our design/coding. It's not purely refactoring related and probably you already know a lot, but maybe it can help :).

*

*Most importantly, we did not always put our code in the right place. There was too many functionality in the view methods, too few in forms and models. I see this problem many times. To handle input, use forms, to format/tweak/... model data, use model methods or properties. Seriously, at one moment I reduced a view of about 150 lines to 20 by just putting code in better places. Improves maintainability and readability very well

*Many code we wrote actually did not really use the full force of python and/or django. For the first one, reading something like Dive Into Python was a great help, for the second one I just tracked down all complex constructs we built (mostly legacy code from 0.96) and looked if there were alternatives in the django docs. Of course, don't waste your time trying to reduce everything to a one-liner, but certainly with legacy code this can help improve readability and maintainability.

*Always look on sites like django-snippets, google code, ... if there are decent existing django projects that can take away a lot of your functionality. Often these projects are looked upon by more people and are therefore more stable and performant. If a project doesn't meet all your demands it can even be a good idea of just adding your requirements yourself instead of doing it all custom for your site.

*Try to keep the application cross-over dependencies minimal. When you would draw a dependency graph (e.g. by linking each app that have foreign keys to each other) it should still be clear and not something where every app is linked to any other app. Typically you'll have some 'helper' apps (e.g. user system, tagging) that are used by many and all other apps are actually only dependent on those apps.

*Write tests, django has an excellent test suite, so use it. Certainly for parts of code that are common to many apps and are likely to change. Really, nothing so annoying as suddenly noticing a bug you actually solved 4 months ago and you have no clue which update since then broke it again.

*Take a second look at database normalization, the django orm model is still tightly coupled to relational databases and so it's an important concept, certainly when you work with models that are likely to be expanded later on.

Concerning real refactoring, the only important tool I can think of is South, can help you a lot if your database scheme changes. Otherwise, like a hint I already gave: write tests to make sure your functionality before and after refactoring remains the same.

A: You can learn about code smells. Some folks say that if your code smells it means you need to consider refactoring.
This is very wide subject in fact. Remeber that:

Premature optimization is the root of all
  evil -- DonaldKnuth

I personally think that this is also valid for (premature) refactoring.
EDIT: this is also a good resource about code smells: http://www.codinghorror.com/blog/2006/05/code-smells.html


text:
Q: Adding column to a resultset in stored procedure I'm working on SP, I want to add a column to a resultset. Normally this would not be a proble, but here I'm using an Exec to fill one temp-table. To that temp-table I want to add one column.
Some prestuff that puts data in one of the temp-tables with some conditions
declare @RowCount int

set @RowCount = 1
create table #Temp_HS (row int IDENTITY (1, 1) NOT NULL, h varchar(30))
Create table #tmpS (K varchar(100),
U varchar(100), Counter int, H varchar(100))

--Puts data in one temp_table with employees
insert into #Temp_HS (h)
select Login from database.dbo.Users
where Old <> 1
and TC in ('A_1', 'A_2')
and Login not in ('Steve', 'Peter', 'Gabs')

--Declaring my counter here, it sets the MaxRow which is 19 in this case
declare @Counter int
set @Counter = (select Max(row) from #Temp_HS)

select * from #Temp_HS
-- Looping, That my RowCount must be less or Equal to Counter which is 19.
while @RowCount <= @Counter
begin

Set User which was originally from the Database Login which is declared as H in the temp table.
declare @user varchar(30)
select @user = h from #Temp_HS where row = @RowCount

Here comes the tricky part, this is the Stored procedure that inserts 3 columns into a temp
table, here I want to add one colum which in this case is h from Temp_HS to the resultset.
INSERT INTO #tmpS
EXEC  Database.dbo.getListCount @user,
param,
param,
param,
'something',
param

set  @RowCount = @RowCount +1
end

drop table #Temp_HS

If you need any further information just ask! :)
Basically I want to add one more column to the results of my Exec SP that inserts the result into a temp_table

A: INSERT INTO .. EXEC requires that the table you are inserting into already exists, e.g.
-- Given this preexisting proc
CREATE PROC dbo.getListCount @user INT, -- other params
AS
   SELECT @User as Col1,
          'SomeVarChar' as Col2
   FROM [SomeTable];

-- In your code, create the temp table to hold the data
CREATE TABLE #tmpS
(
   Col1 INT,
   Col2 NVARCHAR(100),
   NewColumnH VARCHAR(30) -- Add the additional column up front
   -- etc.
);

This is called as
INSERT INTO #tmpS(Col1, Col2)
   EXEC dbo.getListCount, @User;

If you then need to do do further processing on your temp table, do this after the PROC call:
UPDATE ts
   SET NewColumnH = t.h
   FROM #tmpS ts INNER JOIN #Temp_HS th on th.row = @RowCount;

A: Actually inner join doesnt work as desireed on temp tables that is why I used this solution. Since I already had @User in a variable I choose to do this update instead.
UPDATE ts
SET NewColumnH = @User
FROM #tmpS ts
where ts.Column is null


text:
Q: FB share plugin, does not show unless page is reloaded, angular I am trying to use the facebook share plugin. It works fine if I reload the page, but if i go to the page without reloading then the "share button" does not appear. I have tried moving the facebook sdk code into my template and into the head but neither seem to do the trick. Any ideas?
this is the fb code that I have right below the opening  tag

where i implement in my html template
the fbUrl is defined in my controller

A: The problem is the function runs immediately. It's an immediately invocable function expression (IIFE). If you put it in the head, it runs before any of the rest of the document. The only (probably) safe place to put it would be at the end of your document, before the body tag, when all the html elements have been loaded.
If you notice, one of the call is to getElementById but no elements are loaded if you put that into the head and the ID element might not have been loaded if you put it any place else.


text:
Q: R / JSON Can't figure out parsing issue I have a text file full of Tweets stored in JSON format.
"{\"contributors\":null,\"coordinates\":null,\"in_reply_to_user_id\":null,\"truncated\":false,\"text\":\"I find wrapping myself up in my rug more fun than I should.\",\"entities\":{\"hashtags\":[],\"urls\":[],\"user_mentions\":[]},\"place\":null,\"id_str\":\"234702954832220160\",\"favorited\":false,\"geo\":null,\"source\":\"\u003Ca href=\\"http:\/\/blackberry.com\/twitter\\" rel=\\"nofollow\\"\u003ETwitter for BlackBerry\u00ae\u003C\/a\u003E\",\"retweet_count\":0,\"in_reply_to_status_id_str\":null,\"in_reply_to_screen_name\":null,\"created_at\":\"Sun Aug 12 17:28:39 +0000 2012\",\"in_reply_to_user_id_str\":null,\"user\":{\"show_all_inline_media\":true,\"lang\":\"en\",\"friends_count\":200,\"profile_sidebar_border_color\":\"BDDCAD\",\"location\":\"Newcastle\",\"profile_background_image_url_https\":\"https:\/\/si0.twimg.com\/profile_background_images\/613341681\/ed47iwy7apcu7nltbj1y.jpeg\",\"id_str\":\"369637639\",\"listed_count\":0,\"profile_use_background_image\":true,\"profile_image_url_https\":\"https:\/\/si0.twimg.com\/profile_images\/2459865521\/photo_653_normal.jpg\",\"description\":\"Hi, I'm Ellen, but you've probably guessed that by now. You can follow me but I don't know where I'm going.\",\"follow_request_sent\":null,\"following\":null,\"profile_text_color\":\"333333\",\"default_profile\":false,\"profile_background_image_url\":\"http:\/\/a0.twimg.com\/profile_background_images\/613341681\/ed47iwy7apcu7nltbj1y.jpeg\",\"followers_count\":335,\"is_translator\":false,\"time_zone\":\"London\",\"profile_link_color\":\"0084B4\",\"protected\":false,\"created_at\":\"Wed Sep 07 17:56:39 +0000 2011\",\"profile_background_color\":\"9AE4E8\",\"name\":\"ellen\u2020urnbull \",\"default_profile_image\":false,\"contributors_enabled\":false,\"statuses_count\":788,\"geo_enabled\":false,\"notifications\":null,\"profile_background_tile\":false,\"url\":null,\"profile_image_url\":\"http:\/\/a0.twimg.com\/profile_images\/2459865521\/photo_653_normal.jpg\",\"screen_name\":\"ellenteee\",\"id\":369637639,\"verified\":false,\"utc_offset\":0,\"favourites_count\":10,\"profile_sidebar_fill_color\":\"DDFFCC\"},\"retweeted\":false,\"in_reply_to_status_id\":null,\"id\":234702954832220160}
"
"{\"contributors\":null,\"coordinates\":null,\"in_reply_to_user_id\":null,\"truncated\":false,\"text\":\"Goodevening!\",\"entities\":{\"hashtags\":[],\"urls\":[],\"user_mentions\":[]},\"place\":null,\"id_str\":\"234702954828029952\",\"favorited\":false,\"geo\":null,\"source\":\"\u003Ca href=\\"http:\/\/twitter.com\/download\/android\\" rel=\\"nofollow\\"\u003ETwitter for Android\u003C\/a\u003E\",\"retweet_count\":0,\"in_reply_to_status_id_str\":null,\"in_reply_to_screen_name\":null,\"created_at\":\"Sun Aug 12 17:28:39 +0000 2012\",\"in_reply_to_user_id_str\":null,\"user\":{\"show_all_inline_media\":true,\"lang\":\"en\",\"friends_count\":130,\"profile_sidebar_border_color\":\"D3D2CF\",\"location\":\"#3block,St. Rose \",\"profile_background_image_url_https\":\"https:\/\/si0.twimg.com\/profile_background_images\/341819936\/Tyga.jpg\",\"id_str\":\"331869167\",\"listed_count\":0,\"profile_use_background_image\":true,\"profile_image_url_https\":\"https:\/\/si0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png\",\"description\":\" R.I.P Mealey you will be truly miss. Gone but never forgotten. #teamGod #HeatNation\",\"follow_request_sent\":null,\"following\":null,\"profile_text_color\":\"634047\",\"default_profile\":false,\"profile_background_image_url\":\"http:\/\/a0.twimg.com\/profile_background_images\/341819936\/Tyga.jpg\",\"followers_count\":100,\"is_translator\":false,\"time_zone\":\"Central Time (US & Canada)\",\"profile_link_color\":\"088253\",\"protected\":false,\"created_at\":\"Fri Jul 08 21:06:02 +0000 2011\",\"profile_background_color\":\"EDECE9\",\"name\":\"T\u00e9 lu\u00f2 y\u012b \",\"default_profile_image\":true,\"contributors_enabled\":false,\"statuses_count\":16944,\"geo_enabled\":false,\"notifications\":null,\"profile_background_tile\":false,\"url\":null,\"profile_image_url\":\"http:\/\/a0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png\",\"screen_name\":\"Troy_rollupone\",\"id\":331869167,\"verified\":false,\"utc_offset\":-21600,\"favourites_count\":41,\"profile_sidebar_fill_color\":\"E3E2DE\"},\"retweeted\":false,\"in_reply_to_status_id\":null,\"id\":234702954828029952}
"

I scan the file using:
> twit <- scan("twitCapture2.txt","",sep="\n")
Read 4 items
> twit
[1] "\"{\\\"contributors\\\":null,\\\"coordinates\\\":null,\\\"in_reply_to_user_id\\\":null,\\\"truncated\\\":false,\\\"text\\\":\\\"I find wrapping myself up in my rug more fun than I should.\\\",\\\"entities\\\":{\\\"hashtags\\\":[],\\\"urls\\\":[],\\\"user_mentions\\\":[]},\\\"place\\\":null,\\\"id_str\\\":\\\"234702954832220160\\\",\\\"favorited\\\":false,\\\"geo\\\":null,\\\"source\\\":\\\"\\u003Ca href=\\\\\"http:\\/\\/blackberry.com\\/twitter\\\\\" rel=\\\\\"nofollow\\\\\"\\u003ETwitter for BlackBerry\\u00ae\\u003C\\/a\\u003E\\\",\\\"retweet_count\\\":0,\\\"in_reply_to_status_id_str\\\":null,\\\"in_reply_to_screen_name\\\":null,\\\"created_at\\\":\\\"Sun Aug 12 17:28:39 +0000 2012\\\",\\\"in_reply_to_user_id_str\\\":null,\\\"user\\\":{\\\"show_all_inline_media\\\":true,\\\"lang\\\":\\\"en\\\",\\\"friends_count\\\":200,\\\"profile_sidebar_border_color\\\":\\\"BDDCAD\\\",\\\"location\\\":\\\"Newcastle\\\",\\\"profile_background_image_url_https\\\":\\\"https:\\/\\/si0.twimg.com\\/profile_background_images\\/613341681\\/ed47iwy7apcu7nltbj1y.jpeg\\\",\\\"id_str\\\":\\\"369637639\\\",\\\"listed_count\\\":0,\\\"profile_use_background_image\\\":true,\\\"profile_image_url_https\\\":\\\"https:\\/\\/si0.twimg.com\\/profile_images\\/2459865521\\/photo_653_normal.jpg\\\",\\\"description\\\":\\\"Hi, I'm Ellen, but you've probably guessed that by now. You can follow me but I don't know where I'm going.\\\",\\\"follow_request_sent\\\":null,\\\"following\\\":null,\\\"profile_text_color\\\":\\\"333333\\\",\\\"default_profile\\\":false,\\\"profile_background_image_url\\\":\\\"http:\\/\\/a0.twimg.com\\/profile_background_images\\/613341681\\/ed47iwy7apcu7nltbj1y.jpeg\\\",\\\"followers_count\\\":335,\\\"is_translator\\\":false,\\\"time_zone\\\":\\\"London\\\",\\\"profile_link_color\\\":\\\"0084B4\\\",\\\"protected\\\":false,\\\"created_at\\\":\\\"Wed Sep 07 17:56:39 +0000 2011\\\",\\\"profile_background_color\\\":\\\"9AE4E8\\\",\\\"name\\\":\\\"ellen\\u2020urnbull \\\",\\\"default_profile_image\\\":false,\\\"contributors_enabled\\\":false,\\\"statuses_count\\\":788,\\\"geo_enabled\\\":false,\\\"notifications\\\":null,\\\"profile_background_tile\\\":false,\\\"url\\\":null,\\\"profile_image_url\\\":\\\"http:\\/\\/a0.twimg.com\\/profile_images\\/2459865521\\/photo_653_normal.jpg\\\",\\\"screen_name\\\":\\\"ellenteee\\\",\\\"id\\\":369637639,\\\"verified\\\":false,\\\"utc_offset\\\":0,\\\"favourites_count\\\":10,\\\"profile_sidebar_fill_color\\\":\\\"DDFFCC\\\"},\\\"retweeted\\\":false,\\\"in_reply_to_status_id\\\":null,\\\"id\\\":234702954832220160}"
[2] "\""
[3] "\"{\\\"contributors\\\":null,\\\"coordinates\\\":null,\\\"in_reply_to_user_id\\\":null,\\\"truncated\\\":false,\\\"text\\\":\\\"Goodevening!\\\",\\\"entities\\\":{\\\"hashtags\\\":[],\\\"urls\\\":[],\\\"user_mentions\\\":[]},\\\"place\\\":null,\\\"id_str\\\":\\\"234702954828029952\\\",\\\"favorited\\\":false,\\\"geo\\\":null,\\\"source\\\":\\\"\\u003Ca href=\\\\\"http:\\/\\/twitter.com\\/download\\/android\\\\\" rel=\\\\\"nofollow\\\\\"\\u003ETwitter for Android\\u003C\\/a\\u003E\\\",\\\"retweet_count\\\":0,\\\"in_reply_to_status_id_str\\\":null,\\\"in_reply_to_screen_name\\\":null,\\\"created_at\\\":\\\"Sun Aug 12 17:28:39 +0000 2012\\\",\\\"in_reply_to_user_id_str\\\":null,\\\"user\\\":{\\\"show_all_inline_media\\\":true,\\\"lang\\\":\\\"en\\\",\\\"friends_count\\\":130,\\\"profile_sidebar_border_color\\\":\\\"D3D2CF\\\",\\\"location\\\":\\\"#3block,St. Rose \\\",\\\"profile_background_image_url_https\\\":\\\"https:\\/\\/si0.twimg.com\\/profile_background_images\\/341819936\\/Tyga.jpg\\\",\\\"id_str\\\":\\\"331869167\\\",\\\"listed_count\\\":0,\\\"profile_use_background_image\\\":true,\\\"profile_image_url_https\\\":\\\"https:\\/\\/si0.twimg.com\\/sticky\\/default_profile_images\\/default_profile_0_normal.png\\\",\\\"description\\\":\\\" R.I.P Mealey you will be truly miss. Gone but never forgotten. #teamGod #HeatNation\\\",\\\"follow_request_sent\\\":null,\\\"following\\\":null,\\\"profile_text_color\\\":\\\"634047\\\",\\\"default_profile\\\":false,\\\"profile_background_image_url\\\":\\\"http:\\/\\/a0.twimg.com\\/profile_background_images\\/341819936\\/Tyga.jpg\\\",\\\"followers_count\\\":100,\\\"is_translator\\\":false,\\\"time_zone\\\":\\\"Central Time (US & Canada)\\\",\\\"profile_link_color\\\":\\\"088253\\\",\\\"protected\\\":false,\\\"created_at\\\":\\\"Fri Jul 08 21:06:02 +0000 2011\\\",\\\"profile_background_color\\\":\\\"EDECE9\\\",\\\"name\\\":\\\"T\\u00e9 lu\\u00f2 y\\u012b \\\",\\\"default_profile_image\\\":true,\\\"contributors_enabled\\\":false,\\\"statuses_count\\\":16944,\\\"geo_enabled\\\":false,\\\"notifications\\\":null,\\\"profile_background_tile\\\":false,\\\"url\\\":null,\\\"profile_image_url\\\":\\\"http:\\/\\/a0.twimg.com\\/sticky\\/default_profile_images\\/default_profile_0_normal.png\\\",\\\"screen_name\\\":\\\"Troy_rollupone\\\",\\\"id\\\":331869167,\\\"verified\\\":false,\\\"utc_offset\\\":-21600,\\\"favourites_count\\\":41,\\\"profile_sidebar_fill_color\\\":\\\"E3E2DE\\\"},\\\"retweeted\\\":false,\\\"in_reply_to_status_id\\\":null,\\\"id\\\":234702954828029952}"
[4] "\""
>

Then when I try to use fromJSON I get the following errors:
> library(RJSONIO)
>
> twit1<-fromJSON(twit1)
Error in file(con, "r") : invalid 'description' argument
> twit1<-fromJSON(twit1[1])
Error in file(con, "r") : cannot open the connection

> f <- RJSONIO::fromJSON(toJSON(twit1[3]))
> f$text
Error in f$text : $ operator is invalid for atomic vectors
> f <- rjson::fromJSON(toJSON(twit1[3]))
> f$text
Error in f$text : $ operator is invalid for atomic vectors
>

Any ideas on what I'm doing wrong?

A: The "$ operator is invalid for atomic vectors" seems to be caused by the following:
Does not work:
{a: 1, b: 2}
{a: 3, b: 4, c: 5}
Works fine:
{results: [
{a: 1, b: 2},
{a: 3, b: 4, c: 5}
],
status: 1}
(note that you'll need to say data$results$a rather than just data$a)

A: Have you tried
twit1<-fromJSON(twit[1])

A: Looks like your json isn't valid. There are a lot of escape characters. Where did it come from? You can probably get rid of all those escape slashes.

A:
I had a similar issue retrieving an object from window.localStorage
Hopefully this finds someone with a similar issue using local storage

My Problem:
localStorage.myVariable = undefined;
The Solution:
localStorage.removeItem("myVariable");
Explanation:
It was casting localStorage.myVariable as a STRING "undefined" even though I never used quotes!

How My Application Caused Slashes:
This caused a shitton of slashes because I had a string that kept getting stringified! Oops
var stored = localStorage.myVariable ? JSON.parse(localStorage.myVariable) : {};

My ternary if/else check understood localStorage.myVariable to be truthy, since it was a STRING instead of UNDEFINED
I would extend the stored variable (I thought it was an object), then re-encode it using localStorage.myVariable = JSON.stringify(stored); // BAD -- stringifying a string


text:
Q: Query parameter using superagent I'm creating a small Node.js application which calls some REST api´s using Superagent (v5.1.2). I need to send a filter option with a get request.
The API endpoint needs the following structure:
endpoint-url/test?filter=_name eq 'testname'
I´m struggling to achieve this result using superagent with the built-in query method. When I send the request I´ll get all items returned, so the filter option isn't making any effect. Once I test it via postman I´ll get just the specified item returned with the _name = 'testname'.
Here is my code snippet
let name = 'testname';
superagent.get('endpoint-url/test')
           .authBearer(token)
           .query({'filter': '_name eq ' + name})
           .then(res => {
               ...
           })
           .catch(err => {
               ...
           });

A: Here is a minimal working example:
app.js:
const express = require("express");
const app = express();

const memoryDB = {
  users: [{ name: "testname" }, { name: "haha" }],
};

app.get("/test", (req, res) => {
  console.log(req.query);
  const filterName = req.query.filter.split("eq")[1].trim();
  const user = memoryDB.users.find((user) => user.name === filterName);
  res.status(200).json(user);
});

module.exports = app;

app.test.js:
const app = require("./app");
const superagent = require("superagent");
const { expect } = require("chai");

describe("59246379", () => {
  let server;
  before((done) => {
    server = app.listen(3003, () => {
      console.info(`HTTP server is listening on http://localhost:${server.address().port}`);
      done();
    });
  });

  after((done) => {
    server.close(done);
  });
  it("should pass", () => {
    let name = "testname";
    return superagent
      .get("http://localhost:3003/test")
      .query({ filter: "_name eq " + name })
      .then((res) => {
        expect(res.status).to.be.equal(200);
        expect(res.body).to.be.eql({ name: "testname" });
      });
  });
});

Integration test result with coverage report:
  59246379
HTTP server is listening on http://localhost:3003
{ filter: '_name eq testname' }
    ✓ should pass (46ms)

  1 passing (57ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |      100 |      100 |      100 |      100 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59246379


text:
Q: The memory leak caused by `sd_setImage` which is from SDWebImage let path = Bundle.main.path(forResource: deviceGuideGif, ofType: "gif")!
let url:URL = URL.init(fileURLWithPath: path)
imageView.sd_setImage(with: url, completed: nil)

I add this code to a viewController(Let's call it VC1). And when I push VC1 from other viewController,the Memory Use increased.After that, I pop VC1 and the Memory Use didn't decrease.
Now there is a memory leak and I don't know how this happened.Is this a wrong way to use SDWebImage or is there any bugs in SDWebImage?

PS:
It works well if I use this code:
let path = Bundle.main.path(forResource: deviceGuideGif, ofType: "gif")!
let url:URL = URL.init(fileURLWithPath: path)
let imageData = try?Data.init(contentsOf: url)
let image = UIImage.sd_image(with: imageData)
imageView.image = image


text:
Q: How to get a list of assignments and display it in the workflow form? Alfresco Community v5.2 includes some of preconfigured workflows that available on the page /share/page/start-workflow
Among others, there is one that is interested for me - is "Review and Approve (one or more reviewers) - Assign a review task to multiple reviewers". This business process is well suited to the requirements of one of our customers. I copied it and customize accordingly.
Now, for each user's task there is a table (while empty).
When I start the workflow, I can assign executors and also some additional properties is available.
I would like to display all the executors names in this table. What kind of API is available for me in this case?
Where are stored selected executors and how to get a list of them by using JavaScript?

A: Define a form field
'" field id="mswf:prop" set="details" label="details"  read-only="true"  '"
"control template="org/alfresco/components/form/controls/workflow/custom.ftl"
"
Define one more property which will show your table
  Define a custom ftl as form field. And call a repo webscript and get response of  your repo webscript which will return your executors list and you can render it in table in your ftl file