问:
Unable to call function assigned to a variable in python
I have the following code in which the function is not being called and an error is being returned. Following is the code -

```<code>def deleteExistingBackupFiles(step):
    try:
        for setting in step.Setting:
            key = setting['key']
            value = setting['value']
            configTable.update({key: value})
            if os.path.isfile(value):
                os.remove(value)
            elif os.path.isdir(value):
                shutil.rmtree(value)
    except:
        report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

def main():
    scriptPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    configFilePath = os.path.abspath(os.path.realpath(scriptPath + '\config.xml'))
    parsedXML = ET.parse(configFilePath)

    #try:
    for step in parsedXML.iter('Step'):
        for setting in step.iter('Setting'):
            print setting.attrib.get('key')
            print setting.attrib.get('value')
            configTable.update({setting.attrib.get('key'): setting.attrib.get('value')})

    for step in tqdm(parsedXML.iter('Step'), desc='Wordpress Backup Restoration : '):
        methodName = step.attrib.get('methodname')
        result = methodName
        result(step)
</code>```

While trying to execute the last statement, I am getting the following error -

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1585, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 119, in <module>
    main()
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 106, in main
    result(step)
TypeError: 'str' object is not callable
</code>```

The methodName contains DeleteExistingBackupFiles yet it is still not working. Any idea what is going wrong?

Although when I try to execute the following code, it works fine -

```<code>def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

result = (sampleFunc)

result("Hello World!")
</code>```

Have a nice day!

答:
Rather than using the above methods, I utilized a dictionary as stated by @khelwood.

Added the following code before Main()

```<code>commandDispatcher = {
    "deleteExistingBackupFiles" : deleteExistingBackupFiles,
    "overwriteTestSiteData" : overwriteTestSiteData,
    "downloadProdBackup" : downloadProdBackup,
    "importSQL" : importSQL,
    "changeWPOptions" : changeWPOptions,
    "executeWPCli" : executeWPCli
}
</code>```

Source - https://softwareengineering.stackexchange.com/a/182095

Body:
I have the following code in which the function is not being called and an error is being returned. Following is the code -

def deleteExistingBackupFiles(step):
    try:
        for setting in step.Setting:
            key = setting['key']
            value = setting['value']
            configTable.update({key: value})
            if os.path.isfile(value):
                os.remove(value)
            elif os.path.isdir(value):
                shutil.rmtree(value)
    except:
        report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

def main():
    scriptPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    configFilePath = os.path.abspath(os.path.realpath(scriptPath + '\config.xml'))
    parsedXML = ET.parse(configFilePath)

    #try:
    for step in parsedXML.iter('Step'):
        for setting in step.iter('Setting'):
            print setting.attrib.get('key')
            print setting.attrib.get('value')
            configTable.update({setting.attrib.get('key'): setting.attrib.get('value')})

    for step in tqdm(parsedXML.iter('Step'), desc='Wordpress Backup Restoration : '):
        methodName = step.attrib.get('methodname')
        result = methodName
        result(step)

While trying to execute the last statement, I am getting the following error -

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1585, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 119, in <module>
    main()
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 106, in main
    result(step)
TypeError: 'str' object is not callable

The methodName contains DeleteExistingBackupFiles yet it is still not working. Any idea what is going wrong?

Although when I try to execute the following code, it works fine -

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

result = (sampleFunc)

result("Hello World!")

Have a nice day!

Body:
Rather than using the above methods, I utilized a dictionary as stated by @khelwood.

Added the following code before Main()

commandDispatcher = {
    "deleteExistingBackupFiles" : deleteExistingBackupFiles,
    "overwriteTestSiteData" : overwriteTestSiteData,
    "downloadProdBackup" : downloadProdBackup,
    "importSQL" : importSQL,
    "changeWPOptions" : changeWPOptions,
    "executeWPCli" : executeWPCli
}

Source - https://softwareengineering.stackexchange.com/a/182095


来源: stackexchange

问:
Getting 404 while calling rest api developed in Spring
Controller

```<code>package com.example;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ws")
public class Controller {
    @RequestMapping(value="/req", method = RequestMethod.GET,produces="application/json")
    TestBean readBookmarks() {
    TestBean bean = new TestBean("Test", 25);
    return bean;
}
}
</code>```

Web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring MVC Application</display-name>
  <servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>  org.springframework.web.servlet.DispatcherServlet</servlet-class
<load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>App</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
</code>```

App-Servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-
 context.xsd">

<context:component-scan base-package="com.example"/>
</beans>
</code>```

When I try to hit http://localhost:8080/ws/req on browser it says HTTP Status 404.

URL's are registered as observed in logs:

```<code>Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:MathWebApp' did not find a matching property.
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 10 2017 17:21:09 UTC
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.44.0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.12.4
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_111-b14
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/kegupta/Desktop/apache-tomcat-8.0.44/endorsed
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/kegupta/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 480 ms
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.44
Jun 07, 2017 10:35:40 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'App'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization started
Jun 07, 2017 10:35:40 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'App-servlet': startup date [Wed Jun 07 10:35:40 IST 2017]; root of context hierarchy
Jun 07, 2017 10:35:40 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/App-servlet.xml]
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req.*] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req/] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization completed in 617 ms
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1514 ms
</code>```

I am stuck since very long. Any help would be greatly appreciated.

答:
```<code>TestBean readBookmarks() {
TestBean bean = new TestBean("Test", 25);
return bean;
</code>```

This function seems to be lacking @ResponseBody and also TestBean (maybe a custom class) is not something which is serializable by Spring. Can you please try sending String instead of TestBean -- That should work.

Additionally, it is possible that the deployment directory differs from your web.xml config (i.e. something other than App). You can try loading the http://localhost:8080/{Dir}/ws/req where Dir == deployment directory (!= 'App').

The above 2 things should probably resolve your issue.

ContentLicense: CC BY-SA 3.0

Body:
Controller

package com.example;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ws")
public class Controller {
    @RequestMapping(value="/req", method = RequestMethod.GET,produces="application/json")
    TestBean readBookmarks() {
    TestBean bean = new TestBean("Test", 25);
    return bean;
}
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring MVC Application</display-name>
  <servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>  org.springframework.web.servlet.DispatcherServlet</servlet-class
<load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>App</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

App-Servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-
 context.xsd">

<context:component-scan base-package="com.example"/>
</beans>

When I try to hit http://localhost:8080/ws/req on browser it says HTTP Status 404.

URL's are registered as observed in logs:

Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:MathWebApp' did not find a matching property.
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 10 2017 17:21:09 UTC
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.44.0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.12.4
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_111-b14
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/kegupta/Desktop/apache-tomcat-8.0.44/endorsed
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/kegupta/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 480 ms
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.44
Jun 07, 2017 10:35:40 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'App'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization started
Jun 07, 2017 10:35:40 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'App-servlet': startup date [Wed Jun 07 10:35:40 IST 2017]; root of context hierarchy
Jun 07, 2017 10:35:40 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/App-servlet.xml]
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req.*] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req/] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization completed in 617 ms
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1514 ms

I am stuck since very long. Any help would be greatly appreciated.

Body:
TestBean readBookmarks() {
TestBean bean = new TestBean("Test", 25);
return bean;

This function seems to be lacking @ResponseBody and also TestBean (maybe a custom class) is not something which is serializable by Spring. Can you please try sending String instead of TestBean -- That should work.

Additionally, it is possible that the deployment directory differs from your web.xml config (i.e. something other than App). You can try loading the http://localhost:8080/{Dir}/ws/req where Dir == deployment directory (!= 'App').

The above 2 things should probably resolve your issue.


问:
Xlsxwriter merge cells- formatting a pandas dataframe
My program generates a multi index pandas dataframe that I export to excel. After exporting, I used the xlsxwriter functions to set column width, colors etc. So far everything looks good.

I next need to merge few columns but merge function does not retain the text. Have a look at my example sheet.

I need to merge cells B5:D5, B6:D6, B7:D7. Check the desired format below:

But xlsxwriter merge command needs the data to be specified in command
worksheet.merge_range('B4:D4', 'Merged Range', merge_format).

Above excel sheet is just an example. My actual data is very dynamic with greater than 1 experiment. Any workaround for this?

答:
But xlsxwriter merge command needs the data to be specified in command worksheet.merge_range('B4:D4', 'Merged Range', merge_format).

Correct. A workaround would be to read the data the data that you want to merge from the dataframe and use that to write a merge_range().


问:
Facebook API in Flex
If anyone has experience with the Facebook API,
What I’m trying to do is have a logged-in FB user, in my FB app, be able to browse photos uploaded by friends [not necessarily with themselves in those photos -- but just to see photos by their friends]. Is this possible?

Thanks in advance!

答:
I think it's possible. It depends on how you want these photos to be displayed.
I have never connected the facebook API with any Flex app but I have experience with projects that use Iframe to display HTML content in FLex apps. You can find the Iframe project here:
iframe project. In my opinion you can generate these photos in a php script that uses the
facebook API and display its result as Iframe in your Flex application.
I've described the way how the IFrame can be used on my blog here:
Iframe in Flex . I use this approach very often and I've never had any problem with it. </p>

ContentLicense: CC BY-SA 2.5

Title: Facebook API in Flex


问:
C++ generate random number based on mathematical equations.
I have three positive integers

distance1

distance2

distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have  additional information that

20 < distance2 < 90 (EQ2) and

distance1 + distance3 > 8 (EQ3)

I need in C++ to calculate fast three positive random values for distance1, distance2 and distance3 in order to support the equations EQ1, EQ2 and EQ3.

My first approach was to do the following

```<code>    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>
</code>```

Any better approach to do this? Is there any library that can help? Is this the correct way to perform combinations?

答:
First, EQ3 is implied in EQ1+EQ2. (d1+d3=100-d2>100-90=10)

And the core problem is: Do you need a uniform distribution over all possible combinations?

If yes, every combination need to be calculated first (in this case, not in every case).

If no, you can use a more efficient random function.

```<code>#include <iostream>
#include <random>
#include <vector>

std::default_random_engine generator;
std::vector<std::pair<int, int> > results;

void prepareUniformResult()
{
    for(int d2 = 21; d2 <= 89; d2 ++)
        for(int d1 = 1; d1 <= 99-d2; d1 ++)
        results.push_back(std::make_pair(d1, d2));
}

void randomThreeUniform(int &d1, int &d2, int &d3)
{
    std::uniform_int_distribution<int> idist(0, results.size()-1);
    int ind = idist(generator);
    d1 = results.at(ind).first;
    d2 = results.at(ind).second;
    d3 = 100 - d1 - d2;
}

void randomThreeNonUniform(int &d1, int &d2, int &d3)
{
    std::uniform_int_distribution<int> d2dist(21,89);
    d2 = d2dist(generator);
    std::uniform_int_distribution<int> d1dist(1,100-d2-1);
    d1 = d1dist(generator);
    d3 = 100 - d1 - d2;
}
int main()
{
    int d1,d2,d3;

    prepareUniformResult();

    std::cout<<"Non-uniform results:"<<std::endl;
    for(int i=0;i<10;i++)
    {
        randomThreeNonUniform(d1, d2, d3);
        std::cout<<d1<<" "<<d2<<" "<<d3<<std::endl;
    }

    std::cout<<"Uniform results:"<<std::endl;
    for(int i=0;i<10;i++)
    {
        randomThreeUniform(d1, d2, d3);
        std::cout<<d1<<" "<<d2<<" "<<d3<<std::endl;
    }
    return 0;
}
</code>```

We can uniform sampled points (blue points) are more well-distributed than non-uniformed points (orange ones).

Body:
I have three positive integers

distance1

distance2

distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have  additional information that

20 < distance2 < 90 (EQ2) and

distance1 + distance3 > 8 (EQ3)

I need in C++ to calculate fast three positive random values for distance1, distance2 and distance3 in order to support the equations EQ1, EQ2 and EQ3.

My first approach was to do the following

    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>

Any better approach to do this? Is there any library that can help? Is this the correct way to perform combinations?

Body:
First, EQ3 is implied in EQ1+EQ2. (d1+d3=100-d2>100-90=10)

And the core problem is: Do you need a uniform distribution over all possible combinations?

If yes, every combination need to be calculated first (in this case, not in every case).

If no, you can use a more efficient random function.

#include <iostream>
#include <random>
#include <vector>

std::default_random_engine generator;
std::vector<std::pair<int, int> > results;

void prepareUniformResult()
{
    for(int d2 = 21; d2 <= 89; d2 ++)
        for(int d1 = 1; d1 <= 99-d2; d1 ++)
        results.push_back(std::make_pair(d1, d2));
}

void randomThreeUniform(int &d1, int &d2, int &d3)
{
    std::uniform_int_distribution<int> idist(0, results.size()-1);
    int ind = idist(generator);
    d1 = results.at(ind).first;
    d2 = results.at(ind).second;
    d3 = 100 - d1 - d2;
}

void randomThreeNonUniform(int &d1, int &d2, int &d3)
{
    std::uniform_int_distribution<int> d2dist(21,89);
    d2 = d2dist(generator);
    std::uniform_int_distribution<int> d1dist(1,100-d2-1);
    d1 = d1dist(generator);
    d3 = 100 - d1 - d2;
}
int main()
{
    int d1,d2,d3;

    prepareUniformResult();

    std::cout<<"Non-uniform results:"<<std::endl;
    for(int i=0;i<10;i++)
    {
        randomThreeNonUniform(d1, d2, d3);
        std::cout<<d1<<" "<<d2<<" "<<d3<<std::endl;
    }

    std::cout<<"Uniform results:"<<std::endl;
    for(int i=0;i<10;i++)
    {
        randomThreeUniform(d1, d2, d3);
        std::cout<<d1<<" "<<d2<<" "<<d3<<std::endl;
    }
    return 0;
}

We can uniform sampled points (blue points) are more well-distributed than non-uniformed points (orange ones).


问:
how to get specific value from array of data coming from modal
I am getting value from modal which contains array as well like this:

```<code>      <?php var_dump( $myaccount);?>
</code>```

Result:

array (size=1)   0 =>
      object(stdClass)[28]

public 'daysselected' => string '["Monday","Tuesday"]'

public 'due' => string '["2017-06-12","2017-06-13"]'

I am trying to access Monday as single and similarly the date. How can i do so?

I am trying this:

```<code> if(!empty($myaccount)){
     foreach($myaccount as $it){
           echo $it->daysselected[0];//i get '[' only
      }
}
</code>```

答:
```<code>if(!empty($myaccount)){
  foreach($myaccount as $it){
    $days = str_replace(['\'', '"', '[', ']'],'', $it->daysselected );
    $daysSelected = explode(',', $days);
    echo $daysSelected[0];
  }
}
</code>```

try to use this. But error is somewhere in getting of this value.

Body:
I am getting value from modal which contains array as well like this:

      <?php var_dump( $myaccount);?>

Result:

array (size=1)   0 =>
      object(stdClass)[28]

public 'daysselected' => string '["Monday","Tuesday"]'

public 'due' => string '["2017-06-12","2017-06-13"]'

I am trying to access Monday as single and similarly the date. How can i do so?

I am trying this:

 if(!empty($myaccount)){
     foreach($myaccount as $it){
           echo $it->daysselected[0];//i get '[' only
      }
}

Body:
if(!empty($myaccount)){
  foreach($myaccount as $it){
    $days = str_replace(['\'', '"', '[', ']'],'', $it->daysselected );
    $daysSelected = explode(',', $days);
    echo $daysSelected[0];
  }
}

try to use this. But error is somewhere in getting of this value.


问:
how to use distinct to use join two table in mysql
This is my sql query to show hotels with price below 500

```<code>select a.*, b.room_price, b.hotel_id
from hotels a , hotel_room_type b
where a.sub_destination_id=1
and a.destination_id=1 and
a.id = b.hotel_id
and b.room_price BETWEEN 0 AND 500
</code>```

here showing duplicate record
ids 190 have come two time , how can i solve

答:
If I understand your question correctly, you simply want to remove redundant data. You can achieve this by using group by clause.</p>

```<code>SQL> SELECT a.*, b.room_price, b.hotel_id FROM hotels a INNER JOIN  hotel_room_type b ON a.id =b.hotel_id where a.sub_destination_id=1 AND a.destination_id=1 AND b.room_price BETWEEN 0 AND 500 GROUP BY a.id
</code>```

Body:
This is my sql query to show hotels with price below 500

select a.*, b.room_price, b.hotel_id
from hotels a , hotel_room_type b
where a.sub_destination_id=1
and a.destination_id=1 and
a.id = b.hotel_id
and b.room_price BETWEEN 0 AND 500

here showing duplicate record
ids 190 have come two time , how can i solve

Body:
If I understand your question correctly, you simply want to remove redundant data. You can achieve this by using group by clause.

SQL> SELECT a.*, b.room_price, b.hotel_id FROM hotels a INNER JOIN  hotel_room_type b ON a.id =b.hotel_id where a.sub_destination_id=1 AND a.destination_id=1 AND b.room_price BETWEEN 0 AND 500 GROUP BY a.id


问:
Session time out in ASP.NET MVC
I have a problem with my ASP.Net MVC application.
I have the following in my web.config:

```<code>  <authentication mode="Forms">
    <forms loginUrl="~/Login" timeout="525600" />
  </authentication>
  <sessionState mode="InProc" timeout="525600" />
 <machineKey validationKey="" decryptionKey="" validation="SHA1" decryption="AES" />
</code>```

And this in my Global.asax

```<code>    public void Session_OnStart()
    {
        Session.Timeout = 525600;
    }
</code>```

Still some times it works fine but sometimes the session runs out after just 3 - 5 minutes. What am I missing. Is there anything I can do to make session last longer.
Thank you

UPDATE

Some of you suspected that the problem was recycle time but on my production server I don't have the rights necessary to change recycle time to test that.
In the end I fixed it by manually saving session data in database and then when web session expires get data needed from database and put them back in web session.

Thank you for all of your help.

答:
since you set mode to 'inproc' and as you mentioned it works for sometimes and sometimes doesn't work so your application maybe recycled causing your sessions to be restarted

so first make sure that no other code change the session timeout

make sure that application isn't recycled.

Title: Session time out in ASP.NET MVC

Body:
I have a problem with my ASP.Net MVC application.
I have the following in my web.config:

  <authentication mode="Forms">
    <forms loginUrl="~/Login" timeout="525600" />
  </authentication>
  <sessionState mode="InProc" timeout="525600" />
 <machineKey validationKey="" decryptionKey="" validation="SHA1" decryption="AES" />

And this in my Global.asax

    public void Session_OnStart()
    {
        Session.Timeout = 525600;
    }

Still some times it works fine but sometimes the session runs out after just 3 - 5 minutes. What am I missing. Is there anything I can do to make session last longer.
Thank you

UPDATE

Some of you suspected that the problem was recycle time but on my production server I don't have the rights necessary to change recycle time to test that.
In the end I fixed it by manually saving session data in database and then when web session expires get data needed from database and put them back in web session.

Thank you for all of your help.


问:
Not able to access adb in OS X through Terminal, "command not found"
I have installed Android SDK and Eclipse on my Mac system. I am able to program using Eclipse and have created few sample applications. But I am still not able to access adb through the terminal window. I have tried following command in terminal:

```<code>$ pwd
/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools

$ ls
NOTICE.txt  dexdump     llvm-rs-cc-2
aapt        dx          llvm-rs-cc.txt
adb         lib         source.properties
aidl        llvm-rs-cc

$ adb --help
-bash: adb: command not found
</code>```

I have also added the ls output so that you know in which window I am.

答:
Quick Answer

Pasting this command in terminal solves the issue in most cases:

** For Current Terminal Session:

(in macOS) export PATH="~/Library/Android/sdk/platform-tools":$PATH

(in Windows) i will update asap

** Permanently:

(in macOS) edit the ~/.bash_profile using vi ~/.bash_profile and add this line to it: export PATH="~/Library/Android/sdk/platform-tools":$PATH

However, if not, continue reading.

Detailed Answer

Android Debug Bridge, or adb for short, is usually located in Platform Tools and comes with
Android SDK, You simply need to add its location to system path. So system knows about it, and can use it if necessary.

Find ADB's Location

Path to this folder varies by installation scenario, but common ones are:

If you have installed Android Studio, path to ADB would be: (Most Common)

(in macOS) ~/Library/Android/sdk/platform-tools

(in Windows) i will update asap

If you have installed Android Studio somewhere else, determine its location by going to:

(in macOS) Android Studio > Preferences > Appearance And Behavior > System Settings > Android SDK and pay attention to the box that says: Android SDK Location

(in Windows) i will update asap

However Android SDK could be Installed without Android studio, in this case your path might be different, and depends on your installation.

Add it to System Path

When you have determined ADB's location, add it to system, follow this syntax and type it in terminal:

(in macOS)

export PATH="your/path/to/adb/here":$PATH

for example: export PATH="~/Library/Android/sdk/platform-tools":$PATH

Body:
I have installed Android SDK and Eclipse on my Mac system. I am able to program using Eclipse and have created few sample applications. But I am still not able to access adb through the terminal window. I have tried following command in terminal:

$ pwd
/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools

$ ls
NOTICE.txt  dexdump     llvm-rs-cc-2
aapt        dx          llvm-rs-cc.txt
adb         lib         source.properties
aidl        llvm-rs-cc

$ adb --help
-bash: adb: command not found

I have also added the ls output so that you know in which window I am.


问:
How to set property to String
So I've got a bunch of pictures in Resources, 3 pictures of Cat, Dog, and Mouse.
I have to ask the user for the animal they want to see, and then display the correct picture.
Currently I have something like this.

```<code>    Dim animal = InputBox("Enter an animal to show a picture of")
    PictureBox1.Image = My.Resources.animal
</code>```

But I can't set the property to the "animal" string.

How would I do this.

答:
```<code>Dim animalResource As Object = System.Resources.ResourceManager.GetObject(animal)
PictureBox1.Image = TryCast(animalResource, System.Drawing.Image)
</code>```

Title: How to set property to String

Body:
So I've got a bunch of pictures in Resources, 3 pictures of Cat, Dog, and Mouse.
I have to ask the user for the animal they want to see, and then display the correct picture.
Currently I have something like this.

    Dim animal = InputBox("Enter an animal to show a picture of")
    PictureBox1.Image = My.Resources.animal

But I can't set the property to the "animal" string.

How would I do this.


答:
Equation 3 is irrelevant. It is assumed by equation 2.

Distance 1 can go from 1 to 80, Distance 2 can go from 21 to 99 - Distance 1, Distance 3 is then given by 100 - Distance 1 - Distance 2.

So, you need to decide what sort of distribution you want. Do you want a uniform distribution of Distance 1, in which case Distance 2 will have a distribution bunched up to the lower end. Or a uniform distribution on Distance 2?
Or do you want to enumerate the allowed states and select one at random, giving all equal weight? Do that by creating a half matrix with Distance 1 the major axis and Distance 2 the minor.

Title: C++ generate random number based on mathematical equations.


问:
Comparator<File> for "directories-first" order
I'm stumped... Let's say I have this directory tree:

```<code>{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt
</code>```

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

```<code>{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt
</code>```

If I create the straightforward Comparator<File>:

```<code>Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};
</code>```

and I sort, I get this ordering (order3) from lexicographic ordering:

```<code>{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt
</code>```

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

答:
Edit
You have to compare the Base Directory at first level and File name at second level

```<code>import java.io.File;
import java.io.IOException;
import java.util.Comparator;

public class FileComparator implements Comparator<File> {

    @Override
    public int compare(File o1, File o2) {

        int pathCompare = this.getPath(o1).compareTo(this.getPath(o2));
        if (pathCompare != 0) {
            return subPathCompare;
        } else {
            if (o1.isDirectory() && !o2.isDirectory()) {
                return -1;
            } else if (!o1.isDirectory() && o2.isDirectory()) {
                return 1;
            } else {
                return o1.compareTo(o2);
            }
        }
    }

    //maybe there is a better way to speparete path and file name, but it works
    private String getPath(File file) {
        if (file.isFile()) {
            return file.getParent().toLowerCase();
        } else {
            return file.getPath().toLowerCase();
        }
    }
}
</code>```

If the separation of path and file is nessesary, because if one only do:

```<code>        if (o1.isDirectory() && !o2.isDirectory()) {
            return -1;
        } else if (!o1.isDirectory() && o2.isDirectory()) {
            return 1;
        } else {
            return o1.compareTo(o2);
        }
</code>```

the the result would be not case 1, but an other case where all directorys would be the first items, and the files are the last:

```<code>  \dir1\
  \dir2\
  \dir3\
  \dir4\
  \dir1\file1\
  \dir1\file2\
  \dir2\file1\
  \dir2\file2\
</code>```

So my solution is to check first if the two compared files belong to the same directory.

If they do not belong to the same directory, so they are compared by there directory.

If the belong to the same directory, then the sub directorys are "sorted" "before" the normal files.

Body:
I'm stumped... Let's say I have this directory tree:

{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt

If I create the straightforward Comparator<File>:

Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};

and I sort, I get this ordering (order3) from lexicographic ordering:

{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

Body:
Edit
You have to compare the Base Directory at first level and File name at second level

import java.io.File;
import java.io.IOException;
import java.util.Comparator;

public class FileComparator implements Comparator<File> {

    @Override
    public int compare(File o1, File o2) {

        int pathCompare = this.getPath(o1).compareTo(this.getPath(o2));
        if (pathCompare != 0) {
            return subPathCompare;
        } else {
            if (o1.isDirectory() && !o2.isDirectory()) {
                return -1;
            } else if (!o1.isDirectory() && o2.isDirectory()) {
                return 1;
            } else {
                return o1.compareTo(o2);
            }
        }
    }

    //maybe there is a better way to speparete path and file name, but it works
    private String getPath(File file) {
        if (file.isFile()) {
            return file.getParent().toLowerCase();
        } else {
            return file.getPath().toLowerCase();
        }
    }
}

If the separation of path and file is nessesary, because if one only do:

        if (o1.isDirectory() && !o2.isDirectory()) {
            return -1;
        } else if (!o1.isDirectory() && o2.isDirectory()) {
            return 1;
        } else {
            return o1.compareTo(o2);
        }

the the result would be not case 1, but an other case where all directorys would be the first items, and the files are the last:

  \dir1\
  \dir2\
  \dir3\
  \dir4\
  \dir1\file1\
  \dir1\file2\
  \dir2\file1\
  \dir2\file2\

So my solution is to check first if the two compared files belong to the same directory.

If they do not belong to the same directory, so they are compared by there directory.

If the belong to the same directory, then the sub directorys are "sorted" "before" the normal files.


问:
xlsread in Matlab returns NaN even there is no data in Excel
I use xlsread to read a xlsx file. I expect the rawdata will return a 34x3 cell array.

```<code>[raw_num raw_txt rawdata]=xlsread('file.xlsx');
</code>```

The raw_num and raw_txt return correct value, 34x1 cell array and 34x2 cell array.

However, when I check rawdata, it returns 139x6 cell array. It contains not only data in excel file but also NaN element. For the NaN element, there is no data in excel file. I can only assume that I might type something before and then I delete it. But why matlab read it?

The rawdata looks like this:

'a' 'b' 'c' NaN NaN

'd' 'e' 'f' NaN NaN

NaN NaN NaN NaN NaN

How can I avoid this when I use xlsread?

Or how can I remove NaN after I got this matrix?

Thanks for help

答:
You can remove NaN's like below:</p>

```<code>k = {'a' 'b' 'c' NaN NaN}
k(cellfun(@isnan, k)) = [] ;
</code>```

Body:
I use xlsread to read a xlsx file. I expect the rawdata will return a 34x3 cell array.

[raw_num raw_txt rawdata]=xlsread('file.xlsx');

The raw_num and raw_txt return correct value, 34x1 cell array and 34x2 cell array.

However, when I check rawdata, it returns 139x6 cell array. It contains not only data in excel file but also NaN element. For the NaN element, there is no data in excel file. I can only assume that I might type something before and then I delete it. But why matlab read it?

The rawdata looks like this:

'a' 'b' 'c' NaN NaN

'd' 'e' 'f' NaN NaN

NaN NaN NaN NaN NaN

How can I avoid this when I use xlsread?

Or how can I remove NaN after I got this matrix?

Thanks for help

Body:
You can remove NaN's like below:

k = {'a' 'b' 'c' NaN NaN}
k(cellfun(@isnan, k)) = [] ;


问:
How to make circular buttons with Font Awesome icons (and hover effect)?
I am trying to create buttons like the picture below.

I am using stacked Font Awesome icons to put the icons on top of a circle and it looks like this:

(Ignore the gray line at the bottom.  That's a result of poor screenshotting.)

However, as you can see, the icons are a tiny bit off.  Ideally, I want to push them up a bit so they are vertically centered in the circle and either make the circles bigger or the icons smaller to get the nice padding as in the example.  I also want to change the color of the circle which I don't know how to do and add hover effects (like change the icon to white).

Here is my code.

.footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<div class="row footer">
  <!-- FOOTER -->
  <div class="col-md-4"></div>
  <div class="col-md-4 text-center" id="copyright">
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
    </span>

    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-envelope-o fa-stack-1x fa-inverse" aria-hidden="true"></i>
    </span>
  </div>
</div></code>```

答:
the icons are text, it means you can modify them as you would any character.

Just add something like:

```<code>.fa-linkedin, .fa-envelope-o {
  font-size:12px;
}
.fa-circle {color:red;}
</code>```

To your css but I would recomend you to add your own class to your icons insteed of overwritting awesome fonts css as in this fiddle

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create buttons like the picture below.

I am using stacked Font Awesome icons to put the icons on top of a circle and it looks like this:

(Ignore the gray line at the bottom.  That's a result of poor screenshotting.)

However, as you can see, the icons are a tiny bit off.  Ideally, I want to push them up a bit so they are vertically centered in the circle and either make the circles bigger or the icons smaller to get the nice padding as in the example.  I also want to change the color of the circle which I don't know how to do and add hover effects (like change the icon to white).

Here is my code.

.footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
}

<link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>

Body:
the icons are text, it means you can modify them as you would any character.

Just add something like:

.fa-linkedin, .fa-envelope-o {
  font-size:12px;
}
.fa-circle {color:red;}

To your css but I would recomend you to add your own class to your icons insteed of overwritting awesome fonts css as in this fiddle


问:
How to send intent data from main project to library project in android?
I have been trying to send data from my main project to my library project.
My library project is defined in main project so no problem of adding dependency of lib project.one more thread I have found similar to my problem but no luck so far...thread

GetUserprofile is the main project's activity and LockscreenActivity is library project's activity.

I have written code on the main project side

```<code>Intent myIntent = null;
    try {
        myIntent = new Intent(GetUserprofile.this,LockscreenActivity.class);

       myIntent.putExtra("examiddetails",exam_id);

        startActivity(myIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

Now I am getting the data which is examiddetails on the library project by using below code

```<code>Intent intent = getIntent();
    try{
        if(intent != null){
            String Examid = intent.getStringExtra("examiddetails");
        }

    }catch(Exception e){
        System.out.println("getdataFromService exception"+e.toString());
    }
</code>```

I am getting null value of Examid String on the library project.

答:
Create Intent From your application

```<code>Intent myIntent= new Intent(this,YourActivity.class)
myIntent.putExtra("data", "value");
</code>```

Get the Intent From Library

```<code>string intentdata = ((Activity)getContext()).getIntent().getStringExtra("data");
</code>```

Body:
I have been trying to send data from my main project to my library project.
My library project is defined in main project so no problem of adding dependency of lib project.one more thread I have found similar to my problem but no luck so far...thread

GetUserprofile is the main project's activity and LockscreenActivity is library project's activity.

I have written code on the main project side

Intent myIntent = null;
    try {
        myIntent = new Intent(GetUserprofile.this,LockscreenActivity.class);

       myIntent.putExtra("examiddetails",exam_id);

        startActivity(myIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }

Now I am getting the data which is examiddetails on the library project by using below code

Intent intent = getIntent();
    try{
        if(intent != null){
            String Examid = intent.getStringExtra("examiddetails");
        }

    }catch(Exception e){
        System.out.println("getdataFromService exception"+e.toString());
    }

I am getting null value of Examid String on the library project.

Body:
Create Intent From your application

Intent myIntent= new Intent(this,YourActivity.class)
myIntent.putExtra("data", "value");

Get the Intent From Library

string intentdata = ((Activity)getContext()).getIntent().getStringExtra("data");


答:
There are a number of other ways the session could 'expire', e.g.:

User on multiple tabs - logs out on one tab, returns to the other later and expects it to work.

Changes on the server side code could cause the session to be cleared on the server.

Code on the server runs in a web farm (multiple machines) - this can be problematic for 'InProc' sessionstate.

InProc on web farms

If you are on a web farm and your machine keys haven't been set up to match in the web.configs, then your logout might be due to the request going to another server (where the auth cookie won't decrypt and thus be un-authenticated).

InProc doesn't work well in a webfarm situation.  You need to choose another method (SQL Server session state being the other built in option) which will take the session storage to a different location.  There are other 3rd party options for storing the session state on a central machine.

Title: Session time out in ASP.NET MVC


问:
Sitecore Menu Problem
I have a strange error in my Sitecore environment that I've been ignoring since I started development (since it is only a minor inconvenience), and that is the fact that in dealing with large menus near the bottom, they get clipped by the bottom of the browser. Items then should detect the bottom and build upward, I guess, but they just don't. I have gone through the Sitecore Initial Configuration for Internet Explorer document several times.

Has anyone come across this?

Thank you for your time.

答:
Try adding the Sitecore site to your Local Intranet zone in IE, if it's not already.

(btw this is probably a better question for SuperUser, though doubt many sitecore folk monitor that stackexchange)

Title: Sitecore Menu Problem


问:
How to add an id automatically to a related entity
I have a OneToOne relation between 2 entities. One Molecule and one ConcGenotox (conclusion about genotoxicity).

I come from a page where all imformations about one Molecule are displayed and the id of the Molecule is in the address bar.

There is a button to edit a new ConcGenotox about this molecule witch id is always in the address bar.

My question is : How to add automatically the id from the molecule in the id_molecule relation of ConcGenotox when adding a new ConcGenotox ?

ConcGenotox Entity:

```<code>class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
     * })
     *
     */
    private $idMolecule;
</code>```

Molecule Entity :

```<code>class Molecule
{
   /**
    * @ORM\OneToOne(targetEntity="NcstoxBundle\Entity\ConcGenotox", mappedBy="idMolecule")
    */
   private $concGenotox;
</code>```

Contrôler:

```<code>/**
 * Creates a new concGenotox entity.
 *
 * @Route("/new/{id}", name="concgenotox_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, $id)
{
    $concGenotox = new Concgenotox();
    $form = $this->createForm('NcstoxBundle\Form\ConcGenotoxType', $concGenotox);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        var_dump($id);
        $concGenotox->setIdMolecule($id);
        $em->persist($concGenotox);
        $em->flush();

        return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
    }

    return $this->render('concgenotox/new.html.twig', array(
        'concGenotox' => $concGenotox,
        'form' => $form->createView(),
        'id' => $id,
    ));
}
</code>```

I tried to ->setIdMolecule($id) but it give me an error :

```<code>Expected value of type "NcstoxBundle\Entity\Molecule" for association field "NcstoxBundle\Entity\ConcGenotox#$idMolecule", got "string" instead.
</code>```

答:
try this:

```<code>$em = $this->getDoctrine()->getManager();
$molecule = $em->getRepository('YourBundle:Molecule')
                    ->find($id);

$concGenotox->setIdMolecule($molecule);
</code>```

You need to set the entity not the Id

Body:
I have a OneToOne relation between 2 entities. One Molecule and one ConcGenotox (conclusion about genotoxicity).

I come from a page where all imformations about one Molecule are displayed and the id of the Molecule is in the address bar.

There is a button to edit a new ConcGenotox about this molecule witch id is always in the address bar.

My question is : How to add automatically the id from the molecule in the id_molecule relation of ConcGenotox when adding a new ConcGenotox ?

ConcGenotox Entity:

class ConcGenotox
{
    /**
     * @var \Molecule
     *
     * @ORM\OneToOne(targetEntity="Molecule")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
     * })
     *
     */
    private $idMolecule;

Molecule Entity :

class Molecule
{
   /**
    * @ORM\OneToOne(targetEntity="NcstoxBundle\Entity\ConcGenotox", mappedBy="idMolecule")
    */
   private $concGenotox;

Contrôler:

/**
 * Creates a new concGenotox entity.
 *
 * @Route("/new/{id}", name="concgenotox_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, $id)
{
    $concGenotox = new Concgenotox();
    $form = $this->createForm('NcstoxBundle\Form\ConcGenotoxType', $concGenotox);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        var_dump($id);
        $concGenotox->setIdMolecule($id);
        $em->persist($concGenotox);
        $em->flush();

        return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
    }

    return $this->render('concgenotox/new.html.twig', array(
        'concGenotox' => $concGenotox,
        'form' => $form->createView(),
        'id' => $id,
    ));
}

I tried to ->setIdMolecule($id) but it give me an error :

Expected value of type "NcstoxBundle\Entity\Molecule" for association field "NcstoxBundle\Entity\ConcGenotox#$idMolecule", got "string" instead.

Body:
try this:

$em = $this->getDoctrine()->getManager();
$molecule = $em->getRepository('YourBundle:Molecule')
                    ->find($id);

$concGenotox->setIdMolecule($molecule);

You need to set the entity not the Id


问:
build a "fake" stake using startActivity()
I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.

Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.

This is what I got so far when building the stack but I am not sure how to use it in startActivity method

```<code>    Intent detailActivity = new Intent(aContext, DetailsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
    stackBuilder.addNextIntentWithParentStack(detailActivity);
    PendingIntent pendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

答:
The fix that i found to work without having to use onBackPressed was to add a flag to the intent     </p>

```<code>intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

Body:
I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.

Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.

This is what I got so far when building the stack but I am not sure how to use it in startActivity method

    Intent detailActivity = new Intent(aContext, DetailsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
    stackBuilder.addNextIntentWithParentStack(detailActivity);
    PendingIntent pendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

Body:
The fix that i found to work without having to use onBackPressed was to add a flag to the intent

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


问:
Identifying the Number of Positions then Outputting the Positions and Number in another Column

Hi everyone, Im new to VBA and StackOverflow. Currently, I am trying to use VBA to create a process to summarise the data that I have collected.The above photo is a part of the long macro process that I am facing issues with. I need to find the number of unique positions in column "A" (new positions can be added in over time), then output the unique positions into the positions column in column "J". After that, in column "K", I would need to count the number of each unique rank.

As of now, I have the following code to find for a position.

```<code>Sub test ()
Dim Manager as Integer
Sheets("Sheet1").Select
Manager = Application.WorksheetFunction.CountIf(Range("A:A"), "Manager")
'Output the Manager value anywhere as require
End Sub
</code>```

However, I face challenges in identifying the unique positions, counting the unique positions and then outputting the number of unique positions beside the position. Is this even possible in VBA?

Thanks so much

答:
I feel you may be over-complicating things and asking for VBA because you may not know that things can be done without VBA. As I understand the question, you want a count of each position in column A. That can easily be done with a pivot table, without re-inventing the wheel with VBA. Pivot tables are much more powerful and much faster than conventional formulas and DEFINITELY faster than any VBA that you can come up with.

Consider this screenshot:

I've turned column A into an Excel Table object with Insert > Table (or Ctrl-T), so the data can grow easily, but that is optional.

Then I've inserted a pivot table and pulled the Position into the Rows area and pulled it again into the values area, where it is aggregated with a count.

No formulas, no VBA.

If that is not what you need, edit your question and clarify. Otherwise, feel free to mark this as the answer.

Body:
Hi everyone, Im new to VBA and StackOverflow. Currently, I am trying to use VBA to create a process to summarise the data that I have collected.The above photo is a part of the long macro process that I am facing issues with. I need to find the number of unique positions in column "A" (new positions can be added in over time), then output the unique positions into the positions column in column "J". After that, in column "K", I would need to count the number of each unique rank.

As of now, I have the following code to find for a position.

Sub test ()
Dim Manager as Integer
Sheets("Sheet1").Select
Manager = Application.WorksheetFunction.CountIf(Range("A:A"), "Manager")
'Output the Manager value anywhere as require
End Sub

However, I face challenges in identifying the unique positions, counting the unique positions and then outputting the number of unique positions beside the position. Is this even possible in VBA?

Thanks so much


问:
Transfering web site from C to D drive on dedicated server
How can I transfer web site (adjunted with andorid application) from C drive to D drive on a dedicated server which has windows operating system because when I simply move it the application's (the web site works fine) links do not work and I get server error when using the application?

Should I make changes to httpaccess or something similar, per se where is the place where I need to make the changes in the http protocol concering link forwarding from default location in C drive to D (and vice versa)?

答:
You basically need to set the "DocumentRoot" setting inside your webserver application to the correct new value, where the folder with the website itself resides in.
Also, keep your links inside the website "clean", which means, they should all be relative to the document-root ("/").</p>


问:
how to show tick mark and an overlay on image while clicking an image, but when i click other image it should hide and display the same on new image?
i want the image to be overlay-ed with any color and give a tick mark on it(As it is selected) allowing only one image at  a time. while clicking other image it should hide the previous one and show tick and overlay on new image.

```<code><div class="grid-two imageandtext">
                                    <figure>

                                        <img src="assets/images/painting.jpg" class="img-thumbnail">
                                        <div class="caption">
                                            <p>Painting</p>
                                        </div>
                                        <div class="imageandtext image_grid">
                                            <img src="assets/images/photography.jpg" class="img-thumbnail" >
                                            <div class="caption1">
                                                <p>Photography</p>
                                            </div></div>
                                        </figure>
                                    </div>
</code>```

it should display like below image

now it is working like this

https://jsfiddle.net/liza_susan/L8jyum77/

答:
How about this JQuery function:

```<code>$('.image_grid').click(function() {
  $('.image_grid img:nth-of-type(2)').hide();
  $(this).children('img:nth-of-type(2)').show();
});
</code>```

$('.image_grid').click(function() {
  $('.image_grid img:nth-of-type(2)').hide();
  $(this).children('img:nth-of-type(2)').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid-two {
  width: 50%;
  display: inline;
}
.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #000;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}
.imageandtext {
  position: relative;
}
.image_grid {
  display: inline;
  padding-left: 5px;
}
.absolute {
  border: 1px solid black;
  position: absolute;
  left: 0px;
  display: none;
  width: 50%;
  margin: 25%;
}</code>```

Painting

Photography

```

JSFiddle

Body:
i want the image to be overlay-ed with any color and give a tick mark on it(As it is selected) allowing only one image at  a time. while clicking other image it should hide the previous one and show tick and overlay on new image.

Painting

Photography

it should display like below image

now it is working like this

https://jsfiddle.net/liza_susan/L8jyum77/

Body:
How about this JQuery function:

$('.image_grid').click(function() {
  $('.image_grid img:nth-of-type(2)').hide();
  $(this).children('img:nth-of-type(2)').show();
});

$('.image_grid').click(function() {
  $('.image_grid img:nth-of-type(2)').hide();
  $(this).children('img:nth-of-type(2)').show();
});

.grid-two {
  width: 50%;
  display: inline;
}
.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #000;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}
.imageandtext {
  position: relative;
}
.image_grid {
  display: inline;
  padding-left: 5px;
}
.absolute {
  border: 1px solid black;
  position: absolute;
  left: 0px;
  display: none;
  width: 50%;
  margin: 25%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="grid-two imageandtext">
  <figure>
    <div class="imageandtext image_grid">
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
      <div class="caption1">
        <p>Painting</p>
      </div>
      <img src="https://i.stack.imgur.com/Kg1Do.png" class="absolute">
    </div>
    <div class="imageandtext image_grid">
      <img src="http://yaitisme.com/images/getImage.jpg" class="img-thumbnail">
      <div class="caption1">
        <p>Photography</p>
      </div>
      <img src="https://i.stack.imgur.com/Kg1Do.png" class="absolute">
    </div>
  </figure>
</div>

JSFiddle


问:
decode binary from xmlrpc python
I'm new to python and xml-rpc , and I'm stuck with decoding binary data coming from a public service :

the service request response with this code is :

```<code>from xmlrpc.client import Server

import xmlrpc.client

from pprint import pprint

DEV_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'

logFile = open('stat.txt', 'w')

s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')

token = s1.autenticazione.Accedi(DEV_KEY, '')

res = s2.paline.GetStatPassaggi(token)

pprint(res, logFile)
</code>```

response :

```<code>{'id_richiesta': '257a369dbf46e41ba275f8c821c7e1e0',
 'risposta': {'periodi_aggregazione': <xmlrpc.client.Binary object at 0x0000027B7D6E2588>,
              'tempi_attesa_percorsi': <xmlrpc.client.Binary object at 0x0000027B7D9276D8>}}
</code>```

I need to decode these two binary objects , and I'm stuck with this code :

```<code>from xmlrpc.client import Server

import xmlrpc.client

from pprint import pprint

DEV_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx'

logFile = open('stat.txt', 'w')

s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')

token = s1.autenticazione.Accedi(DEV_KEY, '')

res = s2.paline.GetStatPassaggi(token)

dat = xmlrpc.client.Binary(res)
out = xmlrpc.client.Binary.decode(dat)

pprint(out, logFile)
</code>```

that ends in :

Traceback (most recent call last):   File "stat.py", line 18, in

      dat = xmlrpc.client.Binary(res)   File "C:\Users\Leonardo\AppData\Local\Programs\Python\Python35\lib\xmlrpc\client.py",
  line 389, in init
      data.class.name) TypeError: expected bytes or bytearray, not dict

The only doc I found for xmlrpc.client is the one at docs.python.org , but I can't figure out how I could decode these binaries

答:
If the content of res variable (what you get from the 2nd (s2) server) is the response you pasted into the question, then you should modify the last 3 lines of your 2nd snippet to (as you already have 2 Binary objects in the res dictionary):

# ... Existing code
res = s2.paline.GetStatPassaggi(token)

answer = res.get("risposta", dict())
aggregation_periods = answer.get("periodi_aggregazione", xmlrpc.client.Binary())
timeout_paths = answer.get("tempi_attesa_percorsi", xmlrpc.client.Binary())

print(aggregation_periods.data)
print(timeout_paths.data)
```

Notes:

According to [Python.Docs]: xmlrpc.client - Binary Objects (emphasis is mine):

Binary objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:

I wasn't able to connect (and this test the solution), since DEV_KEY is (obviously) fake

Title: decode binary from xmlrpc python

Body:
I'm new to python and xml-rpc , and I'm stuck with decoding binary data coming from a public service :

the service request response with this code is :

from xmlrpc.client import Server

import xmlrpc.client

from pprint import pprint

DEV_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'

logFile = open('stat.txt', 'w')

s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')

token = s1.autenticazione.Accedi(DEV_KEY, '')

res = s2.paline.GetStatPassaggi(token)

pprint(res, logFile)

response :

{'id_richiesta': '257a369dbf46e41ba275f8c821c7e1e0',
 'risposta': {'periodi_aggregazione': <xmlrpc.client.Binary object at 0x0000027B7D6E2588>,
              'tempi_attesa_percorsi': <xmlrpc.client.Binary object at 0x0000027B7D9276D8>}}

I need to decode these two binary objects , and I'm stuck with this code :

from xmlrpc.client import Server

import xmlrpc.client

from pprint import pprint

DEV_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx'

logFile = open('stat.txt', 'w')

s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')

token = s1.autenticazione.Accedi(DEV_KEY, '')

res = s2.paline.GetStatPassaggi(token)

dat = xmlrpc.client.Binary(res)
out = xmlrpc.client.Binary.decode(dat)

pprint(out, logFile)

that ends in :

Traceback (most recent call last):   File "stat.py", line 18, in

      dat = xmlrpc.client.Binary(res)   File "C:\Users\Leonardo\AppData\Local\Programs\Python\Python35\lib\xmlrpc\client.py",
  line 389, in init
      data.class.name) TypeError: expected bytes or bytearray, not dict

The only doc I found for xmlrpc.client is the one at docs.python.org , but I can't figure out how I could decode these binaries

Body:
If the content of res variable (what you get from the 2nd (s2) server) is the response you pasted into the question, then you should modify the last 3 lines of your 2nd snippet to (as you already have 2 Binary objects in the res dictionary):

# ... Existing code
res = s2.paline.GetStatPassaggi(token)

answer = res.get("risposta", dict())
aggregation_periods = answer.get("periodi_aggregazione", xmlrpc.client.Binary())
timeout_paths = answer.get("tempi_attesa_percorsi", xmlrpc.client.Binary())

print(aggregation_periods.data)
print(timeout_paths.data)

Notes:

According to [Python.Docs]: xmlrpc.client - Binary Objects (emphasis is mine):

Binary objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:

I wasn't able to connect (and this test the solution), since DEV_KEY is (obviously) fake


问:
Adding an Image as an icon in a scss file rails?
I'm relatively new to the front-end of rails (usually do back-end), and I'm very lost on adding images to a css file and in lieu my show.haml file.
Here is what I have:

scss file:

```<code>@charset "utf-8";
@import "common";
@import "base_grid";

// teacherSearchForm design ================================
#teacherSearchForm{
  position: relative;
  @include size(100%, 70px);
  margin: 10px 0; padding: 10px 0;
}

.search_option_flipIcon{
  @include size(50px, 50px);
  background: #ddd;
  float: left;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}

.search_option_flipIcon:before{
  color: #888;
  font-family: dripicons;
  font-size: 20px;
}

.tutorial:before{
  content: "\e00d";
}
.zip:before{
  @include size(50px,50px);
  display: block;
  background-image: url('assets/images/users/rsz_zipcode.jpg');
  background-position: 0 0;
  background-repeat: no-repeat;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}
</code>```

show.haml file:

```<code>#teacherSearchForm
  .search_option_flipIcon.prev.tutorial
  #navigation_menu
    #navigation_menu_window
      .search_option_item.fourN#tutorial
        .dripicons.tutorial.oneN
        .search_option_item_title.tenN 使い方ガイドを見る
      .search_option_item.fourN#zip
        .dripicons.zip.oneN
        .search_option_item_title.tenN
          .fiveN= text_field_tag 'zip1', '', :max => '999',  :placeholder => '012',  :id => 'addr_zip1', :class => 'zip_input'
          .twoN -
          .fiveN= text_field_tag 'zip2', '', :max => '9999', :placeholder => '3456', :id => 'addr_zip2', :class => 'zip_input'
      .search_option_item.fourN#option
        .dripicons.option.oneN
        .search_option_item_title.tenN 検索の条件を追加する
  .search_option_flipIcon.next.option

  #search_form
    = form_tag user_searches_path, :remote => true, :authenticity_token => true, :id => 'search_form' do
      = hidden_field_tag "mode", 't'
      = hidden_field_tag "zip1", '', :id => "hidden_zip1"
      = hidden_field_tag "zip2", '', :id => "hidden_zip2"
      #search_form_inner.full
        = render :partial => "user_searches/days"
        = render :partial => "user_searches/subjects"
        = render :partial => "user_searches/sex"
        %input.sixN.btn{:type => "button", :value => "キャンセル"}
        = submit_tag "検索", :class => 'sixN btn'
</code>```

Current result: As seen, the highlighted part has no image.

答: You could use in your scss file 'background-image: asset-url('assets/images/users/rsz_zipcode.jpg');' asset-url return url('precompiled image path')</p>

Body:
I'm relatively new to the front-end of rails (usually do back-end), and I'm very lost on adding images to a css file and in lieu my show.haml file.
Here is what I have:

scss file:

@charset "utf-8";
@import "common";
@import "base_grid";

// teacherSearchForm design ================================
#teacherSearchForm{
  position: relative;
  @include size(100%, 70px);
  margin: 10px 0; padding: 10px 0;
}

.search_option_flipIcon{
  @include size(50px, 50px);
  background: #ddd;
  float: left;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}

.search_option_flipIcon:before{
  color: #888;
  font-family: dripicons;
  font-size: 20px;
}

.tutorial:before{
  content: "\e00d";
}
.zip:before{
  @include size(50px,50px);
  display: block;
  background-image: url('assets/images/users/rsz_zipcode.jpg');
  background-position: 0 0;
  background-repeat: no-repeat;
  line-height: 50px;
  text-align: center;
  &.prev{border-radius: 0 25px 25px 0;}
  &.next{border-radius: 25px 0 0 25px;}
}

show.haml file:

#teacherSearchForm
  .search_option_flipIcon.prev.tutorial
  #navigation_menu
    #navigation_menu_window
      .search_option_item.fourN#tutorial
        .dripicons.tutorial.oneN
        .search_option_item_title.tenN 使い方ガイドを見る
      .search_option_item.fourN#zip
        .dripicons.zip.oneN
        .search_option_item_title.tenN
          .fiveN= text_field_tag 'zip1', '', :max => '999',  :placeholder => '012',  :id => 'addr_zip1', :class => 'zip_input'
          .twoN -
          .fiveN= text_field_tag 'zip2', '', :max => '9999', :placeholder => '3456', :id => 'addr_zip2', :class => 'zip_input'
      .search_option_item.fourN#option
        .dripicons.option.oneN
        .search_option_item_title.tenN 検索の条件を追加する
  .search_option_flipIcon.next.option

  #search_form
    = form_tag user_searches_path, :remote => true, :authenticity_token => true, :id => 'search_form' do
      = hidden_field_tag "mode", 't'
      = hidden_field_tag "zip1", '', :id => "hidden_zip1"
      = hidden_field_tag "zip2", '', :id => "hidden_zip2"
      #search_form_inner.full
        = render :partial => "user_searches/days"
        = render :partial => "user_searches/subjects"
        = render :partial => "user_searches/sex"
        %input.sixN.btn{:type => "button", :value => "キャンセル"}
        = submit_tag "検索", :class => 'sixN btn'

Current result: As seen, the highlighted part has no image.


答:
Do you mean send data to another activity?
I had made same before.

MainProject class

```<code>Intent intent= new intent(getApplication(), LockscreenActivity.class);
intent.putExtra("examiddetails",exam_id);
startActivity(intent);
</code>```

LockscreenActivity class

```<code>Bundle bundle = getIntent().getExtras();
String ExamIdDetails = bundle.getString("examiddetails");
</code>```

Title: How to send intent data from main project to library project in android?

Body:
Do you mean send data to another activity?
I had made same before.

MainProject class

Intent intent= new intent(getApplication(), LockscreenActivity.class);
intent.putExtra("examiddetails",exam_id);
startActivity(intent);

LockscreenActivity class

Bundle bundle = getIntent().getExtras();
String ExamIdDetails = bundle.getString("examiddetails");


问:
Karma Test Cases for CSS File Available or not in a folder or specific path
I need to write test cases for css file so whether css file present or not on specific folder or path..So how to check using karma or jasmine test cases. Need help... Thanks in advance..</p>

答:
You could implement basic node js inside the jasmine test case</p>

```<code>var fs = require('fs');
if (fs.existsSync(path)) {
// Do something
}
</code>```

Body:
You could implement basic node js inside the jasmine test case

var fs = require('fs');
if (fs.existsSync(path)) {
// Do something
}


问:
isBeingDismissed not set in viewWillDisappear:
I have some code to clean up in my viewWillDisappear:, which I only want to use when the view is moving back to the parent view controller.

```<code>- (void)viewWillDisappear:(BOOL)animated
{
    if ([self isMovingFromParentViewController] || [self isBeingDismissed]) {
        NSLog(@"isMovingFromParentViewController or isBeingDismissed");
        // clean up
    }
    [super viewWillDisappear:animated];
}
</code>```

The view can be presented in two ways: it can be pushed by a navigation controller, or presented as a modal view controller (from the same navigation controller). If it's pushed, then popped (pressing the back button), my clean-up code runs. If it it presented as a modal view controller, then dismissed, the code doesn't run.

I dismiss like so:

```<code>[rootViewController dismissModalViewControllerAnimated:YES];
</code>```

My question is: why isn't isBeingDismissed set when I dismiss my view controller?

答:
As @Yuval Tal mentioned, this flag does not work when you're dismissing controller that is embeded inside navigation controller. Here's an extension that I use:

```<code>extension UIViewController
{
    var isAboutToClose: Bool {
        return self.isBeingDismissed ||
               self.isMovingFromParent ||
               self.navigationController?.isBeingDismissed ?? false
    }
}
</code>```

It can be easily extended when you find another case when standard .isBeingDismissed won't work. And if you find, let us, let me know in comments.

Body:
I have some code to clean up in my viewWillDisappear:, which I only want to use when the view is moving back to the parent view controller.

- (void)viewWillDisappear:(BOOL)animated
{
    if ([self isMovingFromParentViewController] || [self isBeingDismissed]) {
        NSLog(@"isMovingFromParentViewController or isBeingDismissed");
        // clean up
    }
    [super viewWillDisappear:animated];
}

The view can be presented in two ways: it can be pushed by a navigation controller, or presented as a modal view controller (from the same navigation controller). If it's pushed, then popped (pressing the back button), my clean-up code runs. If it it presented as a modal view controller, then dismissed, the code doesn't run.

I dismiss like so:

[rootViewController dismissModalViewControllerAnimated:YES];

My question is: why isn't isBeingDismissed set when I dismiss my view controller?

Body:
As @Yuval Tal mentioned, this flag does not work when you're dismissing controller that is embeded inside navigation controller. Here's an extension that I use:

extension UIViewController
{
    var isAboutToClose: Bool {
        return self.isBeingDismissed ||
               self.isMovingFromParent ||
               self.navigationController?.isBeingDismissed ?? false
    }
}

It can be easily extended when you find another case when standard .isBeingDismissed won't work. And if you find, let us, let me know in comments.


问:
How to inline h1 with p to match height?
How can i match the height of the h1 with the p tag?
I want to set the h1 to the left followed by the p on the same base line

.row_cont {
  float: left;
  width: 33.33333333%;
  overflow: hidden;
  border-left: 0.5px solid rgba(0, 0, 0, 0.37);
  padding-right: 15px;
  padding-left: 15px;
}

.row_cont h1 {
  font-size: 70px;
  float: left;
  margin-right: 10px;
}

.row_cont p {
  font-size: 12px;
  margin: 0;
  padding: 0;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="page_container">
  <div class="row">
    <div class="col-md-12">
      <div class="row_cont">
        <h1>1</h1>
        <p>Lorem ipsum dolor sit amet</p>
      </div>
      <div class="row_cont">
        <h1>2</h1>
        <p>Aenean massa. Cum sociis natoque penatibus </p>
      </div>
      <div class="row_cont">
        <h1>3</h1>
        <p>Cras dapibus. Vivamus elementum semper nisi. </p>
      </div>
    </div>
  </div>
</div></code>```

I've tried vertical-align but it's not working, here is my fiddle

答:
EDIT:

this will only be possible by trial and error with the vaules, since the line (and the highest characters in a font) extends above the top of the digits you are using in H1. Basically, use display: inline-block; and vertical-align: top on both containers, then adjust the margin-top settings of both:

```<code>.h1_cont, .p_cont  {
  display: inline-block;
  vertical-align: top;
}
.h1_cont h1 {
   margin-top: 0;
}
.p_cont p {
  margin-top: 5px;
}
</code>```

https://fiddle.jshell.net/rk7nap5u/3/

Body:
How can i match the height of the h1 with the p tag?
I want to set the h1 to the left followed by the p on the same base line

.row_cont {
  float: left;
  width: 33.33333333%;
  overflow: hidden;
  border-left: 0.5px solid rgba(0, 0, 0, 0.37);
  padding-right: 15px;
  padding-left: 15px;
}

.row_cont h1 {
  font-size: 70px;
  float: left;
  margin-right: 10px;
}

.row_cont p {
  font-size: 12px;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

1

Lorem ipsum dolor sit amet

2

Aenean massa. Cum sociis natoque penatibus

3

Cras dapibus. Vivamus elementum semper nisi.

I've tried vertical-align but it's not working, here is my fiddle

Body:
EDIT:

this will only be possible by trial and error with the vaules, since the line (and the highest characters in a font) extends above the top of the digits you are using in H1. Basically, use display: inline-block; and vertical-align: top on both containers, then adjust the margin-top settings of both:

.h1_cont, .p_cont  {
  display: inline-block;
  vertical-align: top;
}
.h1_cont h1 {
   margin-top: 0;
}
.p_cont p {
  margin-top: 5px;
}

https://fiddle.jshell.net/rk7nap5u/3/


问:
R: debugging "undefined columns selected"
When working with R, one of the most common errors is using a non-existent column:

```<code>Error in `[.data.frame`(data, , c(id, nbdays, study, methods)) :
  undefined columns selected
</code>```

For simple code, this is easy to fix, but for complex code and dataframes having hundreds of columns, identifying the offending column can quickly become a nightmare.

Is there a way to figure out which columns are missing?

答:
We can do intersect to find the intersecting columns

```<code>intersect(names(data), c("id", "nbdays", "study", "methods"))
</code>```

Or with setdiff to find the columns not be found

```<code>setdiff(names(data), c("id", "nbdays", "study", "methods"))
</code>```

Body:
When working with R, one of the most common errors is using a non-existent column:

Error in `[.data.frame`(data, , c(id, nbdays, study, methods)) :
  undefined columns selected

For simple code, this is easy to fix, but for complex code and dataframes having hundreds of columns, identifying the offending column can quickly become a nightmare.

Is there a way to figure out which columns are missing?

Body:
We can do intersect to find the intersecting columns

intersect(names(data), c("id", "nbdays", "study", "methods"))

Or with setdiff to find the columns not be found

setdiff(names(data), c("id", "nbdays", "study", "methods"))


问:
laravel-mongodb increment with nested object
I have a post documents that schema looks like

```<code>    {
        "author": {
            "name": "John",
            "gender": 0
        },
        "stats": {
            "likes": 0
        },
        "content": "The new post",
        "updated_at": "2017-06-05 15:15:21",
        "created_at": "2017-06-04 18:10:30",
    }
</code>```

How can I update the stats.likes field through jenssegers/laravel-mongodb

According to the GitHub page, There are a method increment() that can be used.
So I was trying this way

```<code>Post::findOrFail( $request->id )->increment('stats.likes');
</code>```

But got

```<code>ErrorException in HasAttributes.php line 906:
Undefined index: stats.likes
</code>```

However, with the mongo shell, it can work at the code

```<code>db.posts.update( { '_id': ObjectId('5933dc7d4abcf141956a6250') }, { '$inc': { 'stats.likes': 1 } )  )
</code>```

Is that an error caused by nested object?

According to the source code, I found

```<code>/**
 * @inheritdoc
 */
public function increment($column, $amount = 1, array $extra = [], array $options = [])
{
    $query = ['$inc' => [$column => $amount]];

    if (! empty($extra)) {
        $query['$set'] = $extra;
    }

    // Protect
    $this->where(function ($query) use ($column) {
        $query->where($column, 'exists', false);

        $query->orWhereNotNull($column);
    });

    return $this->performUpdate($query, $options);
}
</code>```

If I'm not wrong, the field name stats.likes will pass to the shell directly at the 1st parameter of the method. Why it can just work with the command line?

MongoDB 3.4

jenssegers/laravel-mongodb 3.2

Laravel 5.4

答:
Since I can update a nested object through the artisan command, I wrote a raw expression below alternatively:

```<code>$result = Post::raw(function($collection) use ($request){

    return $collection->findOneAndUpdate([
        '_id' => new \MongoDB\BSON\ObjectID ($request->_id),
    ], [ '$inc' => [ 'stats.likes' => 1 ] ] );

});
</code>```

Notice that you may have effect with db.articles.update(), but the Mongo\Collection doesn't have a method named update(), use findOneAndUpdate, or others instead. (UpdateMany, UpdateOne)

And if the where condition contains _id, you have to wrap your id variable with \MongoDB\BSON\ObjectID object in the case of raw expression.

Body:
I have a post documents that schema looks like

    {
        "author": {
            "name": "John",
            "gender": 0
        },
        "stats": {
            "likes": 0
        },
        "content": "The new post",
        "updated_at": "2017-06-05 15:15:21",
        "created_at": "2017-06-04 18:10:30",
    }

How can I update the stats.likes field through jenssegers/laravel-mongodb

According to the GitHub page, There are a method increment() that can be used.
So I was trying this way

Post::findOrFail( $request->id )->increment('stats.likes');

But got

ErrorException in HasAttributes.php line 906:
Undefined index: stats.likes

However, with the mongo shell, it can work at the code

db.posts.update( { '_id': ObjectId('5933dc7d4abcf141956a6250') }, { '$inc': { 'stats.likes': 1 } )  )

Is that an error caused by nested object?

According to the source code, I found

/**
 * @inheritdoc
 */
public function increment($column, $amount = 1, array $extra = [], array $options = [])
{
    $query = ['$inc' => [$column => $amount]];

    if (! empty($extra)) {
        $query['$set'] = $extra;
    }

    // Protect
    $this->where(function ($query) use ($column) {
        $query->where($column, 'exists', false);

        $query->orWhereNotNull($column);
    });

    return $this->performUpdate($query, $options);
}

If I'm not wrong, the field name stats.likes will pass to the shell directly at the 1st parameter of the method. Why it can just work with the command line?

MongoDB 3.4

jenssegers/laravel-mongodb 3.2

Laravel 5.4

Body:
Since I can update a nested object through the artisan command, I wrote a raw expression below alternatively:

$result = Post::raw(function($collection) use ($request){

    return $collection->findOneAndUpdate([
        '_id' => new \MongoDB\BSON\ObjectID ($request->_id),
    ], [ '$inc' => [ 'stats.likes' => 1 ] ] );

});

Notice that you may have effect with db.articles.update(), but the Mongo\Collection doesn't have a method named update(), use findOneAndUpdate, or others instead. (UpdateMany, UpdateOne)

And if the where condition contains _id, you have to wrap your id variable with \MongoDB\BSON\ObjectID object in the case of raw expression.


问:
log4j2 logging to console only
I have a maven web project which requires logging.

I decided to use log4j2 for that purpose and added the required entries in the pom.xml file

Then I created the log4j2.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <RollingFile name="RollingFile" fileName="${logs.path}/text.log"
            filePattern="${logs.path}/%d{YYYYMMdd}-text.%i.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %-5p %c{1}:%L - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="root" level="info" additivity="false">
            <appender-ref ref="RollingFile" level="info" />
            <appender-ref ref="Console" level="info" />
        </Logger>
        <Root level="info" additivity="false">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>
```

I'm starting tomcat with -Dlogs.path="C:\mylogs", where C:\mylogs exists and has public read/write access.

The console logger is working fine, I can see the correct output in my console, the issue is that the file isn't being created, so I have no logfile, everything gets logged to catalina.out only, and the tomcat startup logs don't show errors for log4j.

What am I missing? is there some additional configuration I need to do in order to log to file?

答: I went through the documentation. You must refer to system properties with sys:, and it seems that tomcat properties are seen as system properties, so I replaced ${logs.path} with ${sys:logs.path} and it worked.

Title: log4j2 logging to console only

Body:
I have a maven web project which requires logging.

I decided to use log4j2 for that purpose and added the required entries in the pom.xml file

Then I created the log4j2.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <RollingFile name="RollingFile" fileName="${logs.path}/text.log"
            filePattern="${logs.path}/%d{YYYYMMdd}-text.%i.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %-5p %c{1}:%L - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="root" level="info" additivity="false">
            <appender-ref ref="RollingFile" level="info" />
            <appender-ref ref="Console" level="info" />
        </Logger>
        <Root level="info" additivity="false">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

I'm starting tomcat with -Dlogs.path="C:\mylogs", where C:\mylogs exists and has public read/write access.

The console logger is working fine, I can see the correct output in my console, the issue is that the file isn't being created, so I have no logfile, everything gets logged to catalina.out only, and the tomcat startup logs don't show errors for log4j.

What am I missing? is there some additional configuration I need to do in order to log to file?