问:
Coding C with pushing char* in to stack
OK I've been working on this code for about a day and a half now and figured I would have figured out why it's not working.

1 - Says I'm passing arguments to a parameter (but executes fine)

2 - Only pushes the first letter of my char* to the stack and not the whole string

```<code>#include <stdio.h>
#include <stdlib.h> //malloc and free
#include <limits.h>
#include <ctype.h>
#include <string.h>

char* getMooki();
void push(char* val, char* val2, int a);
void printStack();
void error(char* msg);

typedef struct node{
    char* data;
    char* date;
    int p_price;
    struct node *pNext;
}node;

node *pTop = NULL;

int main(int charc, char* argv[]){

    int pushVal = 2;
    push("Light","Best", 1);
    printStack();
    push("Moon","Good", 2);
    printStack();
    char* good;
    good = getMooki();
    push(&good,"tada", 3);
    printStack();
    good = getMooki();
    push(&good,"work please", 4);
    printStack();
}

void push(char* val, char* val2, int a){

    if(pTop == NULL){
        pTop = malloc(sizeof(node));
        pTop -> data = val;
        pTop -> date = val2;
        pTop -> p_price = a;
        pTop -> pNext = NULL;
    }else{
        node *pNew = malloc(sizeof(node));
        pNew -> data = val;
        pNew -> date = val2;
        pNew -> p_price = a;
        pNew -> pNext = pTop;
        pTop = pNew;
    }

}

void printStack() {
    //get temporary pointer:
    node *pTemp = pTop;
    if (pTemp == NULL) {
        error("Print error: stack empty");
        return;
    }
    //walk down the stack, printing each value:
    do {
        printf("%s ", pTemp -> data);
        printf("%s ", pTemp -> date);
        printf("%d \n", pTemp -> p_price);
        pTemp = pTemp -> pNext;
    } while (pTemp != NULL);
    printf("\n");
}

void error(char* msg) {
    printf("%s\n", msg);
}

char* getMooki(){
    char* input;
    printf("Enter your string: ");
    scanf("%s", &input);
    return input;
}
</code>```

OK i got the above code working some what.... I know I'm having a memory/pointer issue and I'm having trouble finding related documents to what I'm trying to do since it involves passing a char* in C this is what happens when I run the above code

1 - when I pass &good in to my push function for the stack if I do not pass it as an address (&) i get a segmentation error after I enter my string and hit enter. If i leave the & it will pass and push the new data in to the stack.

2- Problem when I ask for a second string to push in to the stack it changes the data in the previous node and the node in the stack.

Logically I'm passing the same address to the stack so the node's data would naturally point to whatever the new data is that was given to good. But if i don't pass it as an address I get a segmentation error 11

Sorry for noob questions but I've spent a couple days now since getting this to work of digging through forums and youtube videos. Writing it on paper and etc.

答:
```<code>char* getChar(string prompt)
{
    #define BUFFER_LEN (32)
    char buffer[BUFFER_LEN + 1] = {0};  // keep a space for '\0'
    int inputlen = 0;
    char *input;
    printf(" %s", prompt);
    scanf(" %32s", buffer);
    inputlen = strlen(buffer);
    input = malloc(inputlen + 1);
    // assert input != NULL
    memset(input, 0, inputlen + 1);
    strcpy(input, buffer);
    return input;
}
</code>```

Title: Coding C with pushing char* in to stack

Body:
OK I've been working on this code for about a day and a half now and figured I would have figured out why it's not working.

1 - Says I'm passing arguments to a parameter (but executes fine)

2 - Only pushes the first letter of my char* to the stack and not the whole string

#include <stdio.h>
#include <stdlib.h> //malloc and free
#include <limits.h>
#include <ctype.h>
#include <string.h>

char* getMooki();
void push(char* val, char* val2, int a);
void printStack();
void error(char* msg);

typedef struct node{
    char* data;
    char* date;
    int p_price;
    struct node *pNext;
}node;

node *pTop = NULL;

int main(int charc, char* argv[]){

    int pushVal = 2;
    push("Light","Best", 1);
    printStack();
    push("Moon","Good", 2);
    printStack();
    char* good;
    good = getMooki();
    push(&good,"tada", 3);
    printStack();
    good = getMooki();
    push(&good,"work please", 4);
    printStack();
}

void push(char* val, char* val2, int a){

    if(pTop == NULL){
        pTop = malloc(sizeof(node));
        pTop -> data = val;
        pTop -> date = val2;
        pTop -> p_price = a;
        pTop -> pNext = NULL;
    }else{
        node *pNew = malloc(sizeof(node));
        pNew -> data = val;
        pNew -> date = val2;
        pNew -> p_price = a;
        pNew -> pNext = pTop;
        pTop = pNew;
    }

}

void printStack() {
    //get temporary pointer:
    node *pTemp = pTop;
    if (pTemp == NULL) {
        error("Print error: stack empty");
        return;
    }
    //walk down the stack, printing each value:
    do {
        printf("%s ", pTemp -> data);
        printf("%s ", pTemp -> date);
        printf("%d \n", pTemp -> p_price);
        pTemp = pTemp -> pNext;
    } while (pTemp != NULL);
    printf("\n");
}

void error(char* msg) {
    printf("%s\n", msg);
}

char* getMooki(){
    char* input;
    printf("Enter your string: ");
    scanf("%s", &input);
    return input;
}

OK i got the above code working some what.... I know I'm having a memory/pointer issue and I'm having trouble finding related documents to what I'm trying to do since it involves passing a char* in C this is what happens when I run the above code

1 - when I pass &good in to my push function for the stack if I do not pass it as an address (&) i get a segmentation error after I enter my string and hit enter. If i leave the & it will pass and push the new data in to the stack.

2- Problem when I ask for a second string to push in to the stack it changes the data in the previous node and the node in the stack.

Logically I'm passing the same address to the stack so the node's data would naturally point to whatever the new data is that was given to good. But if i don't pass it as an address I get a segmentation error 11

Sorry for noob questions but I've spent a couple days now since getting this to work of digging through forums and youtube videos. Writing it on paper and etc.


来源: stackexchange

问:
GCC 4.9.4 Cross Compiler Build (limits.h issue)
Basic steps leading up to the question:

```<code>cd linux-2.6.35.9/
make ARCH=x86 INSTALL_HDR_PATH=${PREFIX}/${TARGET} headers_install
cd ../

cd build-binutils/
sh ../binutils-2.28/configure --prefix=${PREFIX} --target=${TARGET}
make
make install
cd ../

cd build-gcc/
sh ../gcc-4.9.4/configure --prefix=${PREFIX} --target=${TARGET} --enable-languages=c,c++ --disable-multilib
make all-gcc
make install-gcc
cd ../
</code>```

The problem that I am running into is that what ends up getting installed into ${PREFIX}/lib/gcc/${TARGET}/4.9.4/include-fixed/limits.h doesn't seem to be correct. Specifically, the "fixincludes" bit in building and installing GCC is expecting some directory called "sys-include" that was never put into place and when it's not, the aforementioned limits.h doesn't reference the associated syslimits.h (in the same directory).

If I look in the output of the build/install sequence there's a reference to building this file from components limitx.h, limity.h, and some other bits. This test fails and it just installs the "generic" limits.h that came with GCC (that doesn't include a reference to syslimits.h which uses GCC's #include_next directive to include ${PREFIX}/${TARGET}/include/limits.h that has actual stuff in it I need like NAME_MAX and PATH_MAX).

The bit that is missing from the file is:

```<code>/* This administrivia gets added to the beginning of limits.h
   if the system has its own version of limits.h.  */

/* We use _GCC_LIMITS_H_ because we want this not to match
   any macros that the system's limits.h uses for its own purposes.  */
#ifndef _GCC_LIMITS_H_  /* Terminated in limity.h.  */
#define _GCC_LIMITS_H_

#ifndef _LIBC_LIMITS_H_
/* Use "..." so that we find syslimits.h only in this same directory.  */
#include "syslimits.h"
#endif
</code>```

So is there an option I'm not passing to GCC's configuration script or that I am not passing to something ahead of this step that would create the sys-include directory properly?

[EDIT]

TARGET=i686-redhat-linux (a target triple from "gcc -dumpmachine" on a build server we use for the project)

Possibly more helpful information(?): The packages were simply "wget" pulls from respective archives. I am building on an up-to-date Ubuntu 16.04 installation where I installed libgmp-dev and libmpfr-dev to avoid having to compile them with the compiler source code.

答:
After more digging and trial-and-error I matched up some stuff I started with How to Build a GCC Cross-Compiler with information about an apparently deprecated option --with-headers for configuring GCC. (--with-headers=${PREFIX}/${TARGET}/include/linux) That worked but when I built the compiler support library it complained about missing bits/stdio_lim.h. I found another post here that talks about this problem (you have to go up in the thread a bit) and had mentioned the touching gnu/stubs.h thing from the first page I mentioned.

Added from my own comment below to note that you have to remove the ${PREFIX}/${TARGET}/sys-include directory that gets build after the make install-gcc step or else your normal C headers are going to conflict with the Linux Kernel-specific headers that get included in the search path by default.

Suffice it to say that, after applying a patch to the older Glibc I was using (2.11.3) the entire sequence ends up something like this:

```<code>export TARGET=i686-redhat-linux
export PREFIX=$(pwd)/output
export PATH=${PATH}:${PREFIX}/bin

mkdir build-binutils
mkdir build-gcc
mkdir build-glibc

cd linux-2.6.35.9/
make ARCH=x86 INSTALL_HDR_PATH=${PREFIX}/${TARGET} headers_install
cd ../

cd build-binutils/
sh ../binutils-2.28/configure --prefix=${PREFIX} --target=${TARGET}
make
make install
cd ../

cd build-gcc/
sh ../gcc-4.9.4/configure --prefix=${PREFIX} --target=${TARGET} --enable-languages=c,c++ --disable-multilib --with-headers=${PREFIX}/${TARGET}/include/linux
make all-gcc
make install-gcc
cd ../
rm --recursive --force ${PREFIX}/${TARGET}/sys-include

cd build-glibc/
sh ../glibc-2.11.3/configure --prefix=${PREFIX}/${TARGET} --build=$(gcc -dumpmachine) --host=${TARGET} --target=${TARGET} --disable-multilib libc_cv_forced_unwind=yes libc_cv_c_cleanup=yes
make install-bootstrap-headers=yes install-headers
make csu/subdir_lib
install csu/crt1.o csu/crti.o csu/crtn.o ${PREFIX}/${TARGET}/lib
${TARGET}-gcc -nostdlib -nostartfiles -shared -x c /dev/null -o ${PREFIX}/${TARGET}/lib/libc.so
touch ${PREFIX}/${TARGET}/include/gnu/stubs.h ${PREFIX}/${TARGET}/include/bits/stdio_lim.h
cd ../

cd build-gcc/
make all-target-libgcc
make install-target-libgcc
cd ../

cd build-glibc/
make
make install
cd ../
</code>```

I don't see any pages that actually go to this depth (maybe the Preshing on Programming page isn't actually totally correct?) but I am going to test this configuration and make sure the software builds completely for the target without problems. (I did test NAME_MAX from limits.h in a file and it seemed to work just fine and dandy.)

I also don't really know that I need to put in the --disable-multilib thing but that seems to be what other pages are doing. That chain in the GCC mailing list talks about using --with-newlib or --disable-shared as options but people on the thread could not agree either of those were the correct solution.

If anyone has better insight into this I sure would appreciate a less hacky, more official solution to the problem.

In case anyone was wondering, the patch (there are two) to fix Glibc 2.11.3 was one custom fix for the configure script to work with GNU Make 4+:

```<code>sed -i 's/\(3.79\)/4.* | \1/' glibc-2.11.3/configure
</code>```

... and an actual patch to two files in the library to fix i686 suport:

```<code>patch glibc-2.11.3/nptl/sysdeps/pthread/pt-initfini.c <<__EOF__
@@ -45,6 +45,11 @@
 /* Embed an #include to pull in the alignment and .end directives. */
 asm ("\n#include \"defs.h\"");

+asm ("\n#if defined __i686 && defined __ASSEMBLER__");
+asm ("\n#undef __i686");
+asm ("\n#define __i686 __i686");
+asm ("\n#endif");
+
 /* The initial common code ends here. */
 asm ("\n/*@HEADER_ENDS*/");

__EOF__
patch glibc-2.11.3/sysdeps/unix/sysv/linux/i386/sysdep.h <<__EOF__
@@ -29,6 +29,10 @@
 #include <dl-sysdep.h>
 #include <tls.h>

+#if defined __i686 && defined __ASSEMBLER__
+#undef __i686
+#define __i686 __i686
+#endif

 /* For Linux we can use the system call table in the header file
        /usr/include/asm/unistd.h
__EOF__
</code>```

I got that last patch from here.

ContentLicense: CC BY-SA 3.0

Body:
Basic steps leading up to the question:

cd linux-2.6.35.9/
make ARCH=x86 INSTALL_HDR_PATH=${PREFIX}/${TARGET} headers_install
cd ../

cd build-binutils/
sh ../binutils-2.28/configure --prefix=${PREFIX} --target=${TARGET}
make
make install
cd ../

cd build-gcc/
sh ../gcc-4.9.4/configure --prefix=${PREFIX} --target=${TARGET} --enable-languages=c,c++ --disable-multilib
make all-gcc
make install-gcc
cd ../

The problem that I am running into is that what ends up getting installed into ${PREFIX}/lib/gcc/${TARGET}/4.9.4/include-fixed/limits.h doesn't seem to be correct. Specifically, the "fixincludes" bit in building and installing GCC is expecting some directory called "sys-include" that was never put into place and when it's not, the aforementioned limits.h doesn't reference the associated syslimits.h (in the same directory).

If I look in the output of the build/install sequence there's a reference to building this file from components limitx.h, limity.h, and some other bits. This test fails and it just installs the "generic" limits.h that came with GCC (that doesn't include a reference to syslimits.h which uses GCC's #include_next directive to include ${PREFIX}/${TARGET}/include/limits.h that has actual stuff in it I need like NAME_MAX and PATH_MAX).

The bit that is missing from the file is:

/* This administrivia gets added to the beginning of limits.h
   if the system has its own version of limits.h.  */

/* We use _GCC_LIMITS_H_ because we want this not to match
   any macros that the system's limits.h uses for its own purposes.  */
#ifndef _GCC_LIMITS_H_  /* Terminated in limity.h.  */
#define _GCC_LIMITS_H_

#ifndef _LIBC_LIMITS_H_
/* Use "..." so that we find syslimits.h only in this same directory.  */
#include "syslimits.h"
#endif

So is there an option I'm not passing to GCC's configuration script or that I am not passing to something ahead of this step that would create the sys-include directory properly?

[EDIT]

TARGET=i686-redhat-linux (a target triple from "gcc -dumpmachine" on a build server we use for the project)

Possibly more helpful information(?): The packages were simply "wget" pulls from respective archives. I am building on an up-to-date Ubuntu 16.04 installation where I installed libgmp-dev and libmpfr-dev to avoid having to compile them with the compiler source code.

Body:
After more digging and trial-and-error I matched up some stuff I started with How to Build a GCC Cross-Compiler with information about an apparently deprecated option --with-headers for configuring GCC. (--with-headers=${PREFIX}/${TARGET}/include/linux) That worked but when I built the compiler support library it complained about missing bits/stdio_lim.h. I found another post here that talks about this problem (you have to go up in the thread a bit) and had mentioned the touching gnu/stubs.h thing from the first page I mentioned.

Added from my own comment below to note that you have to remove the ${PREFIX}/${TARGET}/sys-include directory that gets build after the make install-gcc step or else your normal C headers are going to conflict with the Linux Kernel-specific headers that get included in the search path by default.

Suffice it to say that, after applying a patch to the older Glibc I was using (2.11.3) the entire sequence ends up something like this:

export TARGET=i686-redhat-linux
export PREFIX=$(pwd)/output
export PATH=${PATH}:${PREFIX}/bin

mkdir build-binutils
mkdir build-gcc
mkdir build-glibc

cd linux-2.6.35.9/
make ARCH=x86 INSTALL_HDR_PATH=${PREFIX}/${TARGET} headers_install
cd ../

cd build-binutils/
sh ../binutils-2.28/configure --prefix=${PREFIX} --target=${TARGET}
make
make install
cd ../

cd build-gcc/
sh ../gcc-4.9.4/configure --prefix=${PREFIX} --target=${TARGET} --enable-languages=c,c++ --disable-multilib --with-headers=${PREFIX}/${TARGET}/include/linux
make all-gcc
make install-gcc
cd ../
rm --recursive --force ${PREFIX}/${TARGET}/sys-include

cd build-glibc/
sh ../glibc-2.11.3/configure --prefix=${PREFIX}/${TARGET} --build=$(gcc -dumpmachine) --host=${TARGET} --target=${TARGET} --disable-multilib libc_cv_forced_unwind=yes libc_cv_c_cleanup=yes
make install-bootstrap-headers=yes install-headers
make csu/subdir_lib
install csu/crt1.o csu/crti.o csu/crtn.o ${PREFIX}/${TARGET}/lib
${TARGET}-gcc -nostdlib -nostartfiles -shared -x c /dev/null -o ${PREFIX}/${TARGET}/lib/libc.so
touch ${PREFIX}/${TARGET}/include/gnu/stubs.h ${PREFIX}/${TARGET}/include/bits/stdio_lim.h
cd ../

cd build-gcc/
make all-target-libgcc
make install-target-libgcc
cd ../

cd build-glibc/
make
make install
cd ../

I don't see any pages that actually go to this depth (maybe the Preshing on Programming page isn't actually totally correct?) but I am going to test this configuration and make sure the software builds completely for the target without problems. (I did test NAME_MAX from limits.h in a file and it seemed to work just fine and dandy.)

I also don't really know that I need to put in the --disable-multilib thing but that seems to be what other pages are doing. That chain in the GCC mailing list talks about using --with-newlib or --disable-shared as options but people on the thread could not agree either of those were the correct solution.

If anyone has better insight into this I sure would appreciate a less hacky, more official solution to the problem.

In case anyone was wondering, the patch (there are two) to fix Glibc 2.11.3 was one custom fix for the configure script to work with GNU Make 4+:

sed -i 's/\(3.79\)/4.* | \1/' glibc-2.11.3/configure

... and an actual patch to two files in the library to fix i686 suport:

patch glibc-2.11.3/nptl/sysdeps/pthread/pt-initfini.c <<__EOF__
@@ -45,6 +45,11 @@
 /* Embed an #include to pull in the alignment and .end directives. */
 asm ("\n#include \"defs.h\"");

+asm ("\n#if defined __i686 && defined __ASSEMBLER__");
+asm ("\n#undef __i686");
+asm ("\n#define __i686 __i686");
+asm ("\n#endif");
+
 /* The initial common code ends here. */
 asm ("\n/*@HEADER_ENDS*/");

__EOF__
patch glibc-2.11.3/sysdeps/unix/sysv/linux/i386/sysdep.h <<__EOF__
@@ -29,6 +29,10 @@
 #include <dl-sysdep.h>
 #include <tls.h>

+#if defined __i686 && defined __ASSEMBLER__
+#undef __i686
+#define __i686 __i686
+#endif

 /* For Linux we can use the system call table in the header file
        /usr/include/asm/unistd.h
__EOF__

I got that last patch from here.


问:
Getting "No Session found for current thread" exception when using getCurrentSession()
I am using Spring MVC 4.0.6 and Hibernate 4.3.5 . I am trying to insert values to my database table but I am getting this error message:

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread

Currently I am using sessionFactory.getCurrentSession() to save my data , but if I use getSessionFactory().openSession(); it works perfectly. I have heard I should use getCurrentSession instead of getSessionFactory().openSession(); because it creates a new session every time I make a database query.

Could you please see my code below and tell me what I am doing wrong and how to get sessionFactory.getCurrentSession() working ?

GradeServiceImpl:

```<code>@Service
@Transactional
public class GradeServiceImpl implements GradeService {

 @Autowired
 private GradeDao gradeDao;

 @Override
 public void addGrade(Grade grade) {

    gradeDao.addGrade(grade);
 }
}
</code>```

GradeDaoImpl

```<code>@Repository
@Transactional
public class GradeDaoImpl implements GradeDao {

 @Autowired
 private SessionFactory sessionFactory;

 public SessionFactory getSessionFactory() {
    return sessionFactory;
 }

 public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
 }
 @Override
 public void addGrade(Grade grade) {

    sessionFactory.getCurrentSession().save(grade);

 }
}
</code>```

servlet-context.xml

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

   <annotation-driven />
   <context:annotation-config />
   <context:component-scan base-package="com.spring" />

   <resources mapping="/resources/**" location="/resources/" />
   <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
   <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <beans:property name="prefix" value="/WEB-INF/views/" />
      <beans:property name="suffix" value=".jsp" />
   </beans:bean>

   <beans:bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
      <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <beans:property name="url" value="jdbc:mysql://localhost:3306/java" />
      <beans:property name="username" value="root" />
      <beans:property name="password" value="" />
   </beans:bean>

   <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
      <beans:property name="basename" value="resources/messages" />
      <beans:property name="defaultEncoding" value="UTF-8" />
   </beans:bean>

   <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <beans:property name="dataSource" ref="dataSource" />
      <!-- <beans:property name="configLocation">
        <beans:value>classpath:hibernate.cfg.xml</beans:value>
        </beans:property>    -->
      <beans:property name="packagesToScan" value="com.spring" />
      <beans:property name="hibernateProperties">
         <beans:props>
            <beans:prop key="dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
            <beans:prop key="show_sql">true</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
         </beans:props>
      </beans:property>
   </beans:bean>

   <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <beans:property name="sessionFactory" ref="sessionFactory" />
   </beans:bean>

</beans:beans>
</code>```

Web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/root-context.xml</param-value>
   </context-param>
   <!-- Creates the Spring Container shared by all Servlets and Filters -->
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <!-- Processes application requests -->
   <servlet>
      <servlet-name>appServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>appServlet</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>
</code>```

Update - Stack trace

exception

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
</code>```

root cause

```<code>org.hibernate.HibernateException: No Session found for current thread
    org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
    org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    com.spring.org.dao.GradeDaoImpl.addGrade(GradeDaoImpl.java:33)
    com.spring.org.service.GradeServiceImpl.addGrade(GradeServiceImpl.java:25)
    com.spring.org.GradeController.saveGrade(GradeController.java:32)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
</code>```

答:
You should remove the @Transactional annotation on your DAO implementation. Instead in your Service method;

```<code>@Override
@Transactional
public void addGrade(Grade grade) {
    gradeDao.addGrade(grade);
}
</code>```

Only service implementation required @Transactional for all database operations.

Body:
I am using Spring MVC 4.0.6 and Hibernate 4.3.5 . I am trying to insert values to my database table but I am getting this error message:

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread

Currently I am using sessionFactory.getCurrentSession() to save my data , but if I use getSessionFactory().openSession(); it works perfectly. I have heard I should use getCurrentSession instead of getSessionFactory().openSession(); because it creates a new session every time I make a database query.

Could you please see my code below and tell me what I am doing wrong and how to get sessionFactory.getCurrentSession() working ?

GradeServiceImpl:

@Service
@Transactional
public class GradeServiceImpl implements GradeService {

 @Autowired
 private GradeDao gradeDao;

 @Override
 public void addGrade(Grade grade) {

    gradeDao.addGrade(grade);
 }
}

GradeDaoImpl

@Repository
@Transactional
public class GradeDaoImpl implements GradeDao {

 @Autowired
 private SessionFactory sessionFactory;

 public SessionFactory getSessionFactory() {
    return sessionFactory;
 }

 public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
 }
 @Override
 public void addGrade(Grade grade) {

    sessionFactory.getCurrentSession().save(grade);

 }
}

servlet-context.xml

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

   <annotation-driven />
   <context:annotation-config />
   <context:component-scan base-package="com.spring" />

   <resources mapping="/resources/**" location="/resources/" />

   <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <beans:property name="prefix" value="/WEB-INF/views/" />
      <beans:property name="suffix" value=".jsp" />
   </beans:bean>

   <beans:bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
      <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <beans:property name="url" value="jdbc:mysql://localhost:3306/java" />
      <beans:property name="username" value="root" />
      <beans:property name="password" value="" />
   </beans:bean>

   <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
      <beans:property name="basename" value="resources/messages" />
      <beans:property name="defaultEncoding" value="UTF-8" />
   </beans:bean>

   <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <beans:property name="dataSource" ref="dataSource" />

      <beans:property name="packagesToScan" value="com.spring" />
      <beans:property name="hibernateProperties">
         <beans:props>
            <beans:prop key="dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
            <beans:prop key="show_sql">true</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
         </beans:props>
      </beans:property>
   </beans:bean>

   <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <beans:property name="sessionFactory" ref="sessionFactory" />
   </beans:bean>

</beans:beans>

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/root-context.xml</param-value>
   </context-param>

   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

   <servlet>
      <servlet-name>appServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>appServlet</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

Update - Stack trace

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

root cause

org.hibernate.HibernateException: No Session found for current thread
    org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
    org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    com.spring.org.dao.GradeDaoImpl.addGrade(GradeDaoImpl.java:33)
    com.spring.org.service.GradeServiceImpl.addGrade(GradeServiceImpl.java:25)
    com.spring.org.GradeController.saveGrade(GradeController.java:32)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

Body:
You should remove the @Transactional annotation on your DAO implementation. Instead in your Service method;

@Override
@Transactional
public void addGrade(Grade grade) {
    gradeDao.addGrade(grade);
}

Only service implementation required @Transactional for all database operations.


问:
Access denied when trying to download RDP file for Azure VM using Connect button
Click the Connect button to download the RDP file for a VM in Azure Portal results in...

Server Error in '/' Application.

Access is denied.

Description: An error occurred while accessing the resources required
  to serve this request. This may have been caused by an incorrect user
  name and/or password.

Error message 401.1: Logon credentials were not recognized. Make sure
  you are providing the correct user name and password. Otherwise,
  contact the Web server's administrator for help.

Tracing this I think I understand why as I see no creds are passed in any header.

The Request is a POST to

```<code>https://portal.azure.com/api/FileDownload?filename=<myVMfilename>.rdp&mimeType=application%2Frdp&dataType=text
</code>```

This is on a Mac using Safari.

答: It seems Safari can't download Azure VM RDP file, please try to use other browser to download the RDP file, ex. Chrome.</p>

Body:
Click the Connect button to download the RDP file for a VM in Azure Portal results in...

Server Error in '/' Application.

Access is denied.

Description: An error occurred while accessing the resources required
  to serve this request. This may have been caused by an incorrect user
  name and/or password.

Error message 401.1: Logon credentials were not recognized. Make sure
  you are providing the correct user name and password. Otherwise,
  contact the Web server's administrator for help.

Tracing this I think I understand why as I see no creds are passed in any header.

The Request is a POST to

https://portal.azure.com/api/FileDownload?filename=<myVMfilename>.rdp&mimeType=application%2Frdp&dataType=text

This is on a Mac using Safari.


问:
Does it make sense to use a timestamp before saving or when saving to database
Question is pretty forward and it is bothering me for quite some time now. Perhaps any of you has an interesting view on this matter.

When creating an object lets say a memo.
This memo has a string (for the text obviously)
And a user id who has edited said text.

And this memo object is going to be saved to the database.

Is it common to add the current time to the object (eg. add a DateTime field / property) and save that object to db?

Or use the the current time of the database eg. when the row is inserted DateTime.Now in DB?

答:
Although your example is simple one it may represent typical scenario in enterprise environment. So, instead of one user and memo there may be lots of users, lots of tasks to be executed by those users and there are supervisors who are monitoring how users are performing. With that in mind you should try to log everything that you can since supervisors will ask for different productivity reports. And basic elements of such reports are "Start time" and "End time" of activity.

That said, it is of lesser importance which time you are using as long as activities of all users may be compared. Do have in mind that some activities may be executed in different time zones. This leads us to the fact that time used for events (such as start time and end time) should come from common source. Either some middle layer or database.

Implicitly, you need to log user activities. So you will have a method that will have several parameters that are sufficient for capturing user activities. Execution of such method should be on middle or database layer and therefore time registered should be consistent and comparable.

With this approach you have possibility to extend your definition of captured events (not only start and end time but also some other relevant moments).


问:
hub couldn't be resolved in SignalR
I'm working on a signalR project, the project includes a Web API in the API I added my hub class then I created a separate javascript client to work with that
client , through this I got the error said
examhub' Hub could not be resolved. and I don't know why can any help.

My Hub Code :

```<code>public class ExamHub : Hub
{
    public void Send(string name , string message)
    {
        Clients.All.broadcast(name, message);
    }
}
</code>```

Javascript Client :

```<code> <html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"
            integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous"></script>
    <script src="~/Scripts/jquery.signalR-2.2.2.js"></script>
    <script src="http://localhost:51822/signalr/hubs"></script>
    <title>SignalR</title>
</head>
<body>
    <div>
    </div>
    <script type="text/javascript">
        $(function () {
            var exam = $.connection.examHub;

            exam.client.broadcast = function (name, message) {
                alert(name + "" + message);
            }
            $.connection.hub.start().done(function () {
                exam.server.send("Alameer", "Hi");
            });
        });
    </script>

</body>

</html>
</code>```

答:
You probably forgot to include the generated proxy signalr/hubs. Try to add this line to your javascript code:

```<code><script src="signalr/hubs"></script>
</code>```

Title: hub couldn't be resolved in SignalR

Body:
I'm working on a signalR project, the project includes a Web API in the API I added my hub class then I created a separate javascript client to work with that
client , through this I got the error said
examhub' Hub could not be resolved. and I don't know why can any help.

My Hub Code :

public class ExamHub : Hub
{
    public void Send(string name , string message)
    {
        Clients.All.broadcast(name, message);
    }
}

Javascript Client :

    <meta name="viewport" content="width=device-width" />

    <title>SignalR</title>

Body:
You probably forgot to include the generated proxy signalr/hubs. Try to add this line to your javascript code:

<script src="signalr/hubs"></script>


问:
Add function names to a string in Python
I'm just beginning to learn Python on my own, and I'm trying to write a code that will calculate the end time of a jog.

My code so far looks as follows:

```<code>def elapsed(t):
    t = raw_input('Enter time (hh:mm:ss): ')
    th, tm, ts = t.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

def mile(m):
    m = raw_input('How many miles? ')
    return int(m)

start = elapsed('start')
warmup = elapsed('warmup')
wmile = mile('wmile')
tempo = elapsed('tempo')
tmile = mile('tmile')
cooloff = elapsed('cooloff')
cmile = mile('cmile')

hour = (start + warmup * wmile + tempo * tmile + cooloff * cmile) // 3600
minute = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) // 60
second = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) % 60

print('Your run ended at %02d:%02d:%02d' % (hour, minute, second))
</code>```

In this code, the time prompts are all the same: "Enter time (hh:mm:ss):" I want each prompt to refer to its variable name, e.g., "Enter start time (hh:mm:ss)" or "Enter time (hh:mm:ss): (warmup)". Is there a way to do this?

Note: While this may technically be a duplicate, I have examined the similar questions, but decided that both the questions and the answers provided were on the more unspecific side, and therefore decided to ask my question anyway.

答:
Yes, use the input to your function elapsed(t).

Right now it's being overwritten with the return from raw_input()

```<code>def elapsed(t):
    t1 = raw_input('Enter time (hh:mm:ss): ({0})'.format(t))
    th, tm, ts = t1.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600
</code>```

or

```<code>def elapsed(t):
    t1 = raw_input('Enter time (hh:mm:ss): (%s)' % t))
    th, tm, ts = t1.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600
</code>```

Body:
I'm just beginning to learn Python on my own, and I'm trying to write a code that will calculate the end time of a jog.

My code so far looks as follows:

def elapsed(t):
    t = raw_input('Enter time (hh:mm:ss): ')
    th, tm, ts = t.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

def mile(m):
    m = raw_input('How many miles? ')
    return int(m)

start = elapsed('start')
warmup = elapsed('warmup')
wmile = mile('wmile')
tempo = elapsed('tempo')
tmile = mile('tmile')
cooloff = elapsed('cooloff')
cmile = mile('cmile')

hour = (start + warmup * wmile + tempo * tmile + cooloff * cmile) // 3600
minute = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) // 60
second = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) % 60

print('Your run ended at %02d:%02d:%02d' % (hour, minute, second))

In this code, the time prompts are all the same: "Enter time (hh:mm:ss):" I want each prompt to refer to its variable name, e.g., "Enter start time (hh:mm:ss)" or "Enter time (hh:mm:ss): (warmup)". Is there a way to do this?

Note: While this may technically be a duplicate, I have examined the similar questions, but decided that both the questions and the answers provided were on the more unspecific side, and therefore decided to ask my question anyway.

Body:
Yes, use the input to your function elapsed(t).

Right now it's being overwritten with the return from raw_input()

def elapsed(t):
    t1 = raw_input('Enter time (hh:mm:ss): ({0})'.format(t))
    th, tm, ts = t1.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

or

def elapsed(t):
    t1 = raw_input('Enter time (hh:mm:ss): (%s)' % t))
    th, tm, ts = t1.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600


问:
How to activate Unity mode in VMware Workstation？
I create a virtual machine, Linux Mint 18. But I can't activate the Unity mode.
My system is windows 7 64bit. My vmware version is 12 pro.</p>

答:
The following features have reached end of life in Workstation 12 Pro and have been removed:

Unity mode on Linux guest and host operating systems

Integrated Virtual Debugger Visual Studio

Connection to the VMware vCloud Air subscription service (The VMware vCloud Air OnDemand service is still fully supported)

Here is the page.


问:
Are there any Rest frameworks supports Reliability Messaging?
We have a system that use Rest service as communication infrastructure. Recently, We deploy it on a poor network with High latency,Low bandwidth and High packet loss rate, I want to improve it's reliability.I found that there is a dispute on the need for a reliable Rest service.
The articles about this topic I found is below:

Nobody Needs Reliable Messaging

RELIABLE MESSAGING WITH REST

I agree with the latter one, because I have met the same problems mentioned in this article. Are there any opensource Rest frameworks supports Reliability Messaging? Are there any comparison articles about these frameworks?

Thanks a lot.

答: Have you tried the http://restmq.com/ ? As it uses Redis under the hood, you can configure it to persist the state as well.</p>


问:
How to Create an HTML Popup Window Next to Image when Hovering Over It?
I'm attempting to make a webpage where there are several images as links for visiting separate pages, and I want to make a popup show next to the image with a summary, title, and other details of the page in HTML (maybe a button "Read More" or something). I'm trying to create a popup similar to
this one:

I've got my images already, and I can't find a template where there's a separate popup next to the image, because all the image css transition links have the title and text inside the image rather than next to it as a popup. Is this to complicated to do in CSS, or is it possible?

Thanks in advance!  If there is any need for clarification in my question, please ask!

```<code><a href="SecretPlants.html">
<img class="imgLinks" src="file:///E:/Grace/Art/Animation-Computing/Website/ContentTABS/ResourceFiles/Literature/TheSecretsHeldInPlants/SecretLifeofPlantsCover.jpg" alt="Link to Plants Research Paper" height="300">

<a href="EmbraceDifferences.html">
<img class="imgLinks" src="Embrace Differences Cover Image.jpg" alt="Link to Plants Research Paper" height="300">

<a href="Teams of Teams, Hierarchy of Teams, and Hierarchy Essay.html">
<img class="imgLinks" src="Cover.jpg" alt="Link to Hierarchy and Team Critical Essay" height="300">
</code>```

答:
You can just make the popup div with position:absolute and not setting its coordinate to make it popup next to it

for example this one is done without using javascript, using css a:hover

```<code><html>
<head>
    <style>
        #popup0 {
            visibility:hidden;
            position:absolute;
            z-index:1;
        }

        #link0 {
            display:inline;
        }
        #popup0 {
            display:inline;
        }
        #link0:hover #popup0{
            visibility:visible;
            position:absolute;
        }
        #something {
            display:inline;
        }
    </style>
</head>
<body>
    <a href="" id="link0">
        hover here
        <img id="popup0" src="yourfile.png" />
    </a>
    <div id="something">
        other things next to it
    </div>
</body>

</html>
</code>```

Body:
You can just make the popup div with position:absolute and not setting its coordinate to make it popup next to it

for example this one is done without using javascript, using css a:hover

<html>
<head>
    <style>
        #popup0 {
            visibility:hidden;
            position:absolute;
            z-index:1;
        }

        #link0 {
            display:inline;
        }
        #popup0 {
            display:inline;
        }
        #link0:hover #popup0{
            visibility:visible;
            position:absolute;
        }
        #something {
            display:inline;
        }
    </style>
</head>
<body>
    <a href="" id="link0">
        hover here
        <img id="popup0" src="yourfile.png" />
    </a>
    <div id="something">
        other things next to it
    </div>
</body>

</html>

ContentLicense: CC BY-SA 4.0


问:
How to create a event form similar to fb in android
I want to create a event form something like this o exactly like this, is there a library for this kind of a event form or how can i do this? Sorry im newbie in android. I've creating a event app for android. Thank you for any help.

https://ibb.co/bwnTLv

答: You can try gradle files like the one on this link. https://android-arsenal.com/details/1/4247 it's easier and will have a better UI. Or just go to,  https://www.android-arsenal.com to search for more. Thanks.</p>


问:
SQL Server : insert data set into table with an identity column
I have a table with an auto-incrementing identity column. Typically I might insert data as follows

```<code>INSERT INTO [dbo].[table]
DEFAULT VALUES;

SET @value = SCOPE_IDENTITY();
</code>```

This way I know the identity value I've just inserted. However I need to insert a "set" of values into that table. Preferably also be able to identify the values I just inserted. I was hoping something similar to the following would be possible ...

```<code>INSERT INTO dbo.table DEFAULT VALUES
OUTPUT INSERTED.id INTO @output
SELECT SCOPE_IDENTITY()   -- obviously this isn't possible and doesn't actually make sense
FROM @records
WHERE somecolumn IS NULL
</code>```

I know I might need to set identity_insert on ... I would prefer not to if I don't have to. I am also aware that maybe I could also use some sort of recursive CTE, though I haven't used one of those in a while. Any help would be appreciated.

EDIT: to be clear the question I am asking is: how do I insert a "SET" of data into a table with an auto-incrementing identity column. And hopefully identify the values I just inserted in some way.

答:
You are really close:

```<code>INSERT INTO dbo.table
     OUTPUT INSERTED.id INTO @output
     DEFAULT VALUES;

SELECT *
FROM @output;
</code>```

The INSERT puts the values into @output.  You can then reference them.  Remember to define @output as a table variable with a column of the correct type.

Here is a rextester example of it working.

EDIT:

I thought the problem was using @output, because your sample doesn't do that correctly.  If your table has a single identity column, then I don't think that SQL Server provides a single-query mechanism for inserting multiple values, unless you turn off identity insert.

One option is a loop:

```<code>CREATE TABLE t (id int identity);

DECLARE @output table (id int);

DECLARE @i int = 1;

WHILE @i < 10
BEGIN
    INSERT INTO t
         OUTPUT INSERTED.id INTO @output
         DEFAULT VALUES;
    SET @i = @i + 1;
END;

SELECT *
FROM @output;
</code>```

Another option would be to include another column (even a dummy) just so you can insert something.

And finally, perhaps you don't need a table at all.  Perhaps a sequence will suffice for your purposes.

Body:
I have a table with an auto-incrementing identity column. Typically I might insert data as follows

INSERT INTO [dbo].[table]
DEFAULT VALUES;

SET @value = SCOPE_IDENTITY();

This way I know the identity value I've just inserted. However I need to insert a "set" of values into that table. Preferably also be able to identify the values I just inserted. I was hoping something similar to the following would be possible ...

INSERT INTO dbo.table DEFAULT VALUES
OUTPUT INSERTED.id INTO @output
SELECT SCOPE_IDENTITY()   -- obviously this isn't possible and doesn't actually make sense
FROM @records
WHERE somecolumn IS NULL

I know I might need to set identity_insert on ... I would prefer not to if I don't have to. I am also aware that maybe I could also use some sort of recursive CTE, though I haven't used one of those in a while. Any help would be appreciated.

EDIT: to be clear the question I am asking is: how do I insert a "SET" of data into a table with an auto-incrementing identity column. And hopefully identify the values I just inserted in some way.

Body:
You are really close:

INSERT INTO dbo.table
     OUTPUT INSERTED.id INTO @output
     DEFAULT VALUES;

SELECT *
FROM @output;

The INSERT puts the values into @output.  You can then reference them.  Remember to define @output as a table variable with a column of the correct type.

Here is a rextester example of it working.

EDIT:

I thought the problem was using @output, because your sample doesn't do that correctly.  If your table has a single identity column, then I don't think that SQL Server provides a single-query mechanism for inserting multiple values, unless you turn off identity insert.

One option is a loop:

CREATE TABLE t (id int identity);

DECLARE @output table (id int);

DECLARE @i int = 1;

WHILE @i < 10
BEGIN
    INSERT INTO t
         OUTPUT INSERTED.id INTO @output
         DEFAULT VALUES;
    SET @i = @i + 1;
END;

SELECT *
FROM @output;

Another option would be to include another column (even a dummy) just so you can insert something.

And finally, perhaps you don't need a table at all.  Perhaps a sequence will suffice for your purposes.


问:
Removing min from LinkedList
I want to remove 3 from this list but I am not sure where to start. I am storing a sequence of numbers in a Priority Queue that implements a linked list and trying to locate the min and remove it from the priority queue using the removeMin method

```<code>import java.util.Iterator;
import java.util.LinkedList;
public class Test {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {

        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator it = pq.iterator();

        for (int i = 0; i < list.size(); i++) {
            pq.add(list.remove());
        }

        int min = pq.get(0);

        while (it.hasNext()) {
            // help here
        }

        return pq.remove();
    }
</code>```

答:
One simple way to achieve that in one line of code is using the Collections Class:

```<code>list.remove(Collections.min(list));
System.out.println(list); // to test
</code>```

How this work?

list.remove(Object o): Removes the first occurrence of the specified
element from this list, if it is present. If this list does not
contain the element, it is unchanged.

Collections.min(Collection<? extends T> coll): Returns the minimum element of the given collection, according to the natural ordering of its elements.

Furthermore, if you have more than one min value in the collection you may do something like this:

```<code>final Integer min = Collections.min(list);
while(list.contains(min)){ // to remove all min value occurrences in list
      list.remove(min);
}
System.out.println(list); // to test
</code>```

Title: Removing min from LinkedList

Body:
I want to remove 3 from this list but I am not sure where to start. I am storing a sequence of numbers in a Priority Queue that implements a linked list and trying to locate the min and remove it from the priority queue using the removeMin method

import java.util.Iterator;
import java.util.LinkedList;
public class Test {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {

        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator it = pq.iterator();

        for (int i = 0; i < list.size(); i++) {
            pq.add(list.remove());
        }

        int min = pq.get(0);

        while (it.hasNext()) {
            // help here
        }

        return pq.remove();
    }

Body:
One simple way to achieve that in one line of code is using the Collections Class:

list.remove(Collections.min(list));
System.out.println(list); // to test

How this work?

list.remove(Object o): Removes the first occurrence of the specified
element from this list, if it is present. If this list does not
contain the element, it is unchanged.

Collections.min(Collection<? extends T> coll): Returns the minimum element of the given collection, according to the natural ordering of its elements.

Furthermore, if you have more than one min value in the collection you may do something like this:

final Integer min = Collections.min(list);
while(list.contains(min)){ // to remove all min value occurrences in list
      list.remove(min);
}
System.out.println(list); // to test


问:
Spring Data JPA Relationship Annotations
I'm learning Spring Data JPA and having some trouble establishing the relationship between these two tables:

product table with columns id, name, product_type_id

product_type table with columns id, name

A product can have only one type.  A type can be associated with many products.

Where would I use the @OnetoMany and @ManytoOne annotations in my entity classes?

答:
Cassio Mazzochi Molin's answer should work for you after correcting the little mistake he made in the inverse entity (I.e. ProductType class). The @OneToMany should be mapped to the variable type in the owning entity (i.e. Product class) and not productType. So that line should be

```<code>@OneToMany(mappedBy = "type")
</code>```

I will also suggest you pick up a good tutorial book on jpa 2 and study, specially the relationship part because there's lot of rules to it which you can only learn by studying on your own else you will keep asking questions here, trust me.

Pro JPA 2 : Mastering the JAVA persistence API by Apress is a very nice tutorial book that can help you.

Body:
Cassio Mazzochi Molin's answer should work for you after correcting the little mistake he made in the inverse entity (I.e. ProductType class). The @OneToMany should be mapped to the variable type in the owning entity (i.e. Product class) and not productType. So that line should be

@OneToMany(mappedBy = "type")

I will also suggest you pick up a good tutorial book on jpa 2 and study, specially the relationship part because there's lot of rules to it which you can only learn by studying on your own else you will keep asking questions here, trust me.

Pro JPA 2 : Mastering the JAVA persistence API by Apress is a very nice tutorial book that can help you.


问:
xterm not working in mininet
I'm using mininet version 2.1.0. My setup is such that I've to run the mininet
command from a remote machine, e.g.,

ssh -X user@IP python mininet.py

X11 forwarding seems to be fine. X forwarding does not work from the mininet shell only, but it works from the SSH shell.

However, I'm unable to run xterm command on mininet. I'm not getting any
output after running the xterm command.

```<code>mininet> pingall
*** Ping: testing ping reachability
h1 -> h2 h3
h2 -> h1 h3
h3 -> h1 h2
*** Results: 0% dropped (6/6 received)
mininet> xterm h1
mininet> h1 xterm
Warning: This program is an suid-root program or is being run by the root user.
The full text of the error or warning message cannot be safely formatted in
this environment. You may get a more descriptive message by running the
program as a non-root user or by removing the suid bit on the executable.
xterm: Xt error: Can't open display: %s
</code>```

When I start the mininet from my local machine, xterm works and opens up a
new window.

Where should I look for xterm related logs in such case?

I've already spent over a day on this. I also updated mininet version to the latest 2.2.1, but still no success.

Thanks in advance!

答:
The reason "h1 xterm" command is not working under the mininet console is:

two important xterm related environment variables ( $XAUTHORITY , $DISPLAY ) are not passing over to the mininet console, if you run : "h1 echo $DISPLAY $XAUTHORITY" ; both variables will return blank.

In order to keep the host environment variables unchanged, add -E argument to the mn command. "sudo -E mn" , and then you will be able to run "h1 xterm" successfully.

Title: xterm not working in mininet

Body:
I'm using mininet version 2.1.0. My setup is such that I've to run the mininet
command from a remote machine, e.g.,

ssh -X user@IP python mininet.py

X11 forwarding seems to be fine. X forwarding does not work from the mininet shell only, but it works from the SSH shell.

However, I'm unable to run xterm command on mininet. I'm not getting any
output after running the xterm command.

mininet> pingall
*** Ping: testing ping reachability
h1 -> h2 h3
h2 -> h1 h3
h3 -> h1 h2
*** Results: 0% dropped (6/6 received)
mininet> xterm h1
mininet> h1 xterm
Warning: This program is an suid-root program or is being run by the root user.
The full text of the error or warning message cannot be safely formatted in
this environment. You may get a more descriptive message by running the
program as a non-root user or by removing the suid bit on the executable.
xterm: Xt error: Can't open display: %s

When I start the mininet from my local machine, xterm works and opens up a
new window.

Where should I look for xterm related logs in such case?

I've already spent over a day on this. I also updated mininet version to the latest 2.2.1, but still no success.

Thanks in advance!


问:
Python3 - retrieving Facebook html
```<code><a class="_2wma" href="https://www.facebook.com/SMRTCorpSG/?ref=page_internal">SMRT</a>
</code>```

I am trying to retrieve the text in the  however when i tired using the method below, the outcome is an empty list [] . Did i make a mistake here?

```<code>r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
name = soup.find_all("a",{"class": "_2wma"})
print(name)
name2 = soup.find_all("a", {"href": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})
print(name2)
</code>```

答:
```<code>soup.find("a", attrs={"class": "_2wma"}).text
</code>```

Title: Python3 - retrieving Facebook html

Body:
SMRT

I am trying to retrieve the text in the  however when i tired using the method below, the outcome is an empty list [] . Did i make a mistake here?

r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
name = soup.find_all("a",{"class": "_2wma"})
print(name)
name2 = soup.find_all("a", {"href": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})
print(name2)


问:
Fade In Fade Out Android Animation in Java
I want to have a 2 second animation of an ImageView that spends 1000ms fading in and then 1000ms fading out.

Here's what I have so far in my ImageView constructor:

```<code>Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(1000);

Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);

AnimationSet animation = new AnimationSet(true);
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
</code>```

When I run that animation, nothing shows up. However, when I remove one of the alpha animations, the behavior works as expected.

Things I have already tried:

Every conceivable combination of setFillBefore, setFillAfter, and setFillEnabled.

Adding a LinearInterpolator to the AnimationSet.

答:
If you use Animator for make animation you can

anim (directory) -> fade_out.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
    android:propertyName="alpha"
    android:valueFrom="0"
    android:valueTo="1"
    xmlns:android="http://schemas.android.com/apk/res/android"/>
</code>```

In java

```<code>Animator animator = AnimatorInflater.loadAnimator(context, R.animator.fade_out);
animator.setTarget(the_view_you_want_to_animation);
animator.setDuration(1000);
animator.start();
</code>```

Other way to make animation fade out with only java code is

```<code>ObjectAnimator fadeOut = ObjectAnimator.ofFloat(the_view_you_want_to_animation, "alpha",  1f, 0);
fadeOut.setDuration(2000);
fadeOut.start();
</code>```

Body:
I want to have a 2 second animation of an ImageView that spends 1000ms fading in and then 1000ms fading out.

Here's what I have so far in my ImageView constructor:

Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(1000);

Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);

AnimationSet animation = new AnimationSet(true);
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);

When I run that animation, nothing shows up. However, when I remove one of the alpha animations, the behavior works as expected.

Things I have already tried:

Every conceivable combination of setFillBefore, setFillAfter, and setFillEnabled.

Adding a LinearInterpolator to the AnimationSet.

Body:
If you use Animator for make animation you can

anim (directory) -> fade_out.xml

<?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
    android:propertyName="alpha"
    android:valueFrom="0"
    android:valueTo="1"
    xmlns:android="http://schemas.android.com/apk/res/android"/>

In java

Animator animator = AnimatorInflater.loadAnimator(context, R.animator.fade_out);
animator.setTarget(the_view_you_want_to_animation);
animator.setDuration(1000);
animator.start();

Other way to make animation fade out with only java code is

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(the_view_you_want_to_animation, "alpha",  1f, 0);
fadeOut.setDuration(2000);
fadeOut.start();


问:
Sharing a struct safely amongst multiple threads
Under Windows/C++, if I have a struct:

```<code>struct ListItem {
    ListItem* next;
    ListItem* prev;
    ...
}
</code>```

together with multiple threads running in both the main process and in several dynamically loaded DLLs, and all of those threads need to share the above struct, how do I stop them stomping on each other? Something like:

```<code>ListItem* list = ...

A

list->next = ...

B
</code>```

What do I put at A and B to prevent no more than one thread at a time running list->next = ...?

答:
Use Windows Mutex objects where you have multiple processes that may access one resource.

If your threads are all on one process then you can use EnterCriticalSection / LeaveCriticalSection.

ContentLicense: CC BY-SA 2.5

Body:
Under Windows/C++, if I have a struct:

struct ListItem {
    ListItem* next;
    ListItem* prev;
    ...
}

together with multiple threads running in both the main process and in several dynamically loaded DLLs, and all of those threads need to share the above struct, how do I stop them stomping on each other? Something like:

ListItem* list = ...

A

list->next = ...

B

What do I put at A and B to prevent no more than one thread at a time running list->next = ...?


问:
Locating a button from outside its activity
I have Firebaselistener class and it listens for the value of 1. When this value is reached I want the button drawable to change. Originally I had this all set up in my main activity and it worked OK using:

```<code>if(dls==1){
m.setBackground(getResources().getDrawable(R.drawable.buttonbkground2));
}
</code>```

from with in my main activity using a valueEventlistener and listening for the value.

But now I've set up a class to do the same thing I can't access the button ids from the main activity.

```<code>public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button mButton;
Context c;

public RewardValueListener() {

}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);
    Log.d("tag", "Value: " + dls);
    i = Integer.parseInt(dls);
    if (i == 1) {

        Log.d("tag", "Congrats " + i);

        mButton.setBackground(c.getResources().getDrawable(R.drawable.buttonbkground2));

    }
}
@Override
public void onCancelled(FirebaseError firebaseError) {

}
</code>```

***Code edit with cricket's answer included

```<code>  public void getButton(Button button,Context context) {
    mButton = button;
    c=context;
  }
</code>```

I know it's something to do with calling the view but how and where do I call it?

Edit

Thanks to @cricket_007 for his answer which works great. Now I have the code working is there away to call my Listener class to change all the buttons in my main activity rather than just one.

I can get it to work if for every button if write the code this way but is there a way to condense it so I don't have to overflow my main activity:

```<code>  RewardValueListener reward1 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward1);
    reward1.getButton(mstreaming,mcontext);
    RewardValueListener reward2 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward2);
    reward2.getButton(mcustom,mcontext);
    RewardValueListener reward3 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward3);
    reward3.getButton(mlauncher,mcontext);
    RewardValueListener reward4 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward4);
    reward4.getButton(mmovies,mcontext);
  etc etc...
</code>```

答:
You need to pass the button in as a field into your listener either in constructing it or as a setter.

This should work:

```<code>public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button button;
public RewardValueListener(Button button) {
    this.button = button;
}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);
    Log.d("tag", "test before if " + dls);
    i = Integer.parseInt(dls);
    if (i==1){

        Log.d("tag", "test after if " + i);
     button.setBackground(getResources().getDrawable(R.drawable.buttonbkground2));

    }
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}
</code>```

Body:
I have Firebaselistener class and it listens for the value of 1. When this value is reached I want the button drawable to change. Originally I had this all set up in my main activity and it worked OK using:

if(dls==1){
m.setBackground(getResources().getDrawable(R.drawable.buttonbkground2));
}

from with in my main activity using a valueEventlistener and listening for the value.

But now I've set up a class to do the same thing I can't access the button ids from the main activity.

public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button mButton;
Context c;

public RewardValueListener() {

}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);
    Log.d("tag", "Value: " + dls);
    i = Integer.parseInt(dls);
    if (i == 1) {

        Log.d("tag", "Congrats " + i);

        mButton.setBackground(c.getResources().getDrawable(R.drawable.buttonbkground2));

    }
}
@Override
public void onCancelled(FirebaseError firebaseError) {

}

***Code edit with cricket's answer included

  public void getButton(Button button,Context context) {
    mButton = button;
    c=context;
  }

I know it's something to do with calling the view but how and where do I call it?

Edit

Thanks to @cricket_007 for his answer which works great. Now I have the code working is there away to call my Listener class to change all the buttons in my main activity rather than just one.

I can get it to work if for every button if write the code this way but is there a way to condense it so I don't have to overflow my main activity:

  RewardValueListener reward1 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward1);
    reward1.getButton(mstreaming,mcontext);
    RewardValueListener reward2 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward2);
    reward2.getButton(mcustom,mcontext);
    RewardValueListener reward3 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward3);
    reward3.getButton(mlauncher,mcontext);
    RewardValueListener reward4 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward4);
    reward4.getButton(mmovies,mcontext);
  etc etc...

Body:
You need to pass the button in as a field into your listener either in constructing it or as a setter.

This should work:

public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button button;
public RewardValueListener(Button button) {
    this.button = button;
}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);
    Log.d("tag", "test before if " + dls);
    i = Integer.parseInt(dls);
    if (i==1){

        Log.d("tag", "test after if " + i);
     button.setBackground(getResources().getDrawable(R.drawable.buttonbkground2));

    }
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}


问:
Creating a new directory using Kotlin, Mkdir() doesn't work
```<code>var filename = "blesson.txt"
var wallpaperDirectory = File("/sdcard/Wallpaper")
 wallpaperDirectory.mkdirs()
val outputFile = File(wallpaperDirectory, filename)
val fos = FileOutputStream(outputFile)
</code>```

I am trying to make a new directory on an Android device using Kotlin, but the function mkdirs() doesn't work.

```<code>var filename = "blesson.txt"
var wallpaperDirectory = File(Environment.getExternalStorageDirectory().absolutePath)//("/sdcard/Wallpaper")
wall
val outputFile = File(wallpaperDirectory, filename)
val fos = FileOutputStream(outputFile)
</code>```

I have tried this also, it is not making a new directory
Any help is welcome

答:
This works perfectly on Kotlin</p>

```<code>class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var filename = "blesson.txt"
    // create a File object for the parent directory
    val wallpaperDirectory = File("/sdcard/Wallpaper/")
    // have the object build the directory structure, if needed.
    wallpaperDirectory.mkdirs()
    // create a File object for the output file
    val outputFile = File(wallpaperDirectory, filename)
    // now attach the OutputStream to the file object, instead of a String representation
    try {
      val fos = FileOutputStream(outputFile)
    } catch (e: FileNotFoundException) {
      e.printStackTrace()
    }

  }
}
</code>```

Body:
var filename = "blesson.txt"
var wallpaperDirectory = File("/sdcard/Wallpaper")
 wallpaperDirectory.mkdirs()
val outputFile = File(wallpaperDirectory, filename)
val fos = FileOutputStream(outputFile)

I am trying to make a new directory on an Android device using Kotlin, but the function mkdirs() doesn't work.

var filename = "blesson.txt"
var wallpaperDirectory = File(Environment.getExternalStorageDirectory().absolutePath)//("/sdcard/Wallpaper")
wall
val outputFile = File(wallpaperDirectory, filename)
val fos = FileOutputStream(outputFile)

I have tried this also, it is not making a new directory
Any help is welcome

Body:
This works perfectly on Kotlin

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var filename = "blesson.txt"
    // create a File object for the parent directory
    val wallpaperDirectory = File("/sdcard/Wallpaper/")
    // have the object build the directory structure, if needed.
    wallpaperDirectory.mkdirs()
    // create a File object for the output file
    val outputFile = File(wallpaperDirectory, filename)
    // now attach the OutputStream to the file object, instead of a String representation
    try {
      val fos = FileOutputStream(outputFile)
    } catch (e: FileNotFoundException) {
      e.printStackTrace()
    }

  }
}


问:
Getting "fatal error: all goroutines are asleep - deadlock!" when using sync.WaitGroup
I'm trying to spin off a set of goroutines, and then wait for them all to finish.

```<code>import "sync"

func doWork(wg sync.WaitGroup) error {
    defer wg.Done()
    // Do some heavy lifting... request URL's or similar
    return nil
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go doWork(wg)
    }
    wg.Wait()
}
</code>```

However when I run this code I get the following error:

```<code>fatal error: all goroutines are asleep - deadlock!

goroutine 16 [semacquire]:
sync.runtime_Semacquire(0xc20818c658)
    /usr/local/Cellar/go/1.3/libexec/src/pkg/runtime/sema.goc:199 +0x30
sync.(*WaitGroup).Wait(0xc2080544e0)
    /usr/local/Cellar/go/1.3/libexec/src/pkg/sync/waitgroup.go:129 +0x14b
main.main()
    /Users/kevin/code/vrusability/scripts/oculus_share_ratings.go:150 +0x398
</code>```

I'm confused because I wrote it pretty much exactly as the documentation example demonstrates.

答:
As @Kevin mentioned, you will need to pass a reference to your WaitGroup. This is actually the one thing I do not like about WaitGroup because you would be mixing your concurrency logic with your business logic.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

Here is an example:

```<code>func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

Parallelize(func1, func2)  // a 1 b 2 c 3
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Body:
I'm trying to spin off a set of goroutines, and then wait for them all to finish.

import "sync"

func doWork(wg sync.WaitGroup) error {
    defer wg.Done()
    // Do some heavy lifting... request URL's or similar
    return nil
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go doWork(wg)
    }
    wg.Wait()
}

However when I run this code I get the following error:

fatal error: all goroutines are asleep - deadlock!

goroutine 16 [semacquire]:
sync.runtime_Semacquire(0xc20818c658)
    /usr/local/Cellar/go/1.3/libexec/src/pkg/runtime/sema.goc:199 +0x30
sync.(*WaitGroup).Wait(0xc2080544e0)
    /usr/local/Cellar/go/1.3/libexec/src/pkg/sync/waitgroup.go:129 +0x14b
main.main()
    /Users/kevin/code/vrusability/scripts/oculus_share_ratings.go:150 +0x398

I'm confused because I wrote it pretty much exactly as the documentation example demonstrates.

Body:
As @Kevin mentioned, you will need to pass a reference to your WaitGroup. This is actually the one thing I do not like about WaitGroup because you would be mixing your concurrency logic with your business logic.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

Here is an example:

func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

Parallelize(func1, func2)  // a 1 b 2 c 3

If you would like to use it, you can find it here https://github.com/shomali11/util


问:
JS Rendering within React
I have javascript - webscraper. I added this in my component folder within my ReactJS app. I am trying to Render this into the web page.

The JSX components I used the  within other compoents to render it.

How do I get the output from this webscraper javascript into the webpage.
I know the console.log() statement must be changed, but I don't know how to proceed.

```<code>var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false})

nightmare
  .goto('http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/')

  //.wait('#entry-content')
  .evaluate(function () {
    var ht = document.querySelector('li');
    //return ht[0];
    //return (ht.split(/\r\n|\r|\n/).length);
    //check = document.querySelectorAll('#bodyblock > ul >li').length;
    //return check;
    //var ht1 = document.querySelectorAll('#bodyblock > ul > li ').innerText[5];
    //return ht1;
    return ht;

  })
  .end()
  .then(function (result) {
    console.log(result)
  })
  .catch(function (error) {
    console.log('Search failed:', error);
  });
</code>```

答:
Your above function just gets data, then if you want to display the data on react page, you will have to use this.setState() and the page will be re-rendered.

I assume that the above function works well, then you can use something like this: (according to React Component's Life Cycle):

```<code>import React from 'react';
import Nightmare from 'nightmare';

export default class MyClass extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            resultFromScraping: '',
        }
    }

    componentWillMount() {
        var nightmare = Nightmare({ show: false});

        nightmare
            .goto('http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/')

            //.wait('#entry-content')
            .evaluate(function () {
                var ht = document.querySelector('li');
                //return ht[0];
                //return (ht.split(/\r\n|\r|\n/).length);
                //check = document.querySelectorAll('#bodyblock > ul >li').length;
                //return check;
                //var ht1 = document.querySelectorAll('#bodyblock > ul > li ').innerText[5];
                //return ht1;
                return ht;

            })
            .end()
            .then( (result) => { //here we use lexical binding, to bind this callback function to the current react component
                console.log(result);
                this.setState({
                    resultFromScraping: JSON.stringify(result), //this is just an example, you can do whatever you want with the result here
                });

            })
            .catch(function (error) {
                console.log('Search failed:', error);
            });
    }

    render() {
        return (
            <div>{this.state.resultFromScraping}</div>
        );
    }
}
</code>```

If you have any error, please post here then we can find a solution, thanks ^^ !

Title: JS Rendering within React

Body:
I have javascript - webscraper. I added this in my component folder within my ReactJS app. I am trying to Render this into the web page.

The JSX components I used the  within other compoents to render it.

How do I get the output from this webscraper javascript into the webpage.
I know the console.log() statement must be changed, but I don't know how to proceed.

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false})

nightmare
  .goto('http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/')

  //.wait('#entry-content')
  .evaluate(function () {
    var ht = document.querySelector('li');
    //return ht[0];
    //return (ht.split(/\r\n|\r|\n/).length);
    //check = document.querySelectorAll('#bodyblock > ul >li').length;
    //return check;
    //var ht1 = document.querySelectorAll('#bodyblock > ul > li ').innerText[5];
    //return ht1;
    return ht;

  })
  .end()
  .then(function (result) {
    console.log(result)
  })
  .catch(function (error) {
    console.log('Search failed:', error);
  });

Body:
Your above function just gets data, then if you want to display the data on react page, you will have to use this.setState() and the page will be re-rendered.

I assume that the above function works well, then you can use something like this: (according to React Component's Life Cycle):

import React from 'react';
import Nightmare from 'nightmare';

export default class MyClass extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            resultFromScraping: '',
        }
    }

    componentWillMount() {
        var nightmare = Nightmare({ show: false});

        nightmare
            .goto('http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/')

            //.wait('#entry-content')
            .evaluate(function () {
                var ht = document.querySelector('li');
                //return ht[0];
                //return (ht.split(/\r\n|\r|\n/).length);
                //check = document.querySelectorAll('#bodyblock > ul >li').length;
                //return check;
                //var ht1 = document.querySelectorAll('#bodyblock > ul > li ').innerText[5];
                //return ht1;
                return ht;

            })
            .end()
            .then( (result) => { //here we use lexical binding, to bind this callback function to the current react component
                console.log(result);
                this.setState({
                    resultFromScraping: JSON.stringify(result), //this is just an example, you can do whatever you want with the result here
                });

            })
            .catch(function (error) {
                console.log('Search failed:', error);
            });
    }

    render() {
        return (
            <div>{this.state.resultFromScraping}</div>
        );
    }
}

If you have any error, please post here then we can find a solution, thanks ^^ !


问:
A file does not exist in the file system but .gitignore still lists that file
I had a few files which I added to .git Ignore when they existed but they do not exist anymore. However, they are still listed in .gitignore.

when I do command git rm --cached it says that file does not exist for the obvious reasons.

Is there a way that I can tell .gitignore so stop ignoring files that just do not exist anymore?

答: Just remove the lines from .gitignore and you'll be fine.</p>


问:
how to enlist multiple records filtered by checkedlistbox
i have a data grid view  and checked list box. checked list box is populated from database items i want create  filter using checked list box's items means to populate data grid view by checking checked list box's items now the problem is that data grid view show only only one record corresponds to checked item but does not display multiple records if multiple checkbox items are checked.

```<code>        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=DESKTOP-50ME4GC\SQLEXPRESS;Initial Catalog=autolab;Integrated Security=True";
        if (pn.CheckedItems.Count != 0)
        {
            // If so, loop through all checked items and print results.
            string s = "";
            int x;
            for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
            {
                s = s + pn.CheckedItems[x].ToString();
            }
            connection.Open();
            SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN ('" + s + "') ", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataTable tbl = new DataTable();

           adapter.Fill(tbl);

            dt.DataSource = tbl;

            connection.Close();

        }
</code>```

答:
It seems that your for loop concatenates list items. Try to write

```<code>s = s + pn.CheckedItems[x].ToString() + ", ";
</code>```

Do not forget to remove last ", " after the loop.

Body:
i have a data grid view  and checked list box. checked list box is populated from database items i want create  filter using checked list box's items means to populate data grid view by checking checked list box's items now the problem is that data grid view show only only one record corresponds to checked item but does not display multiple records if multiple checkbox items are checked.

        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=DESKTOP-50ME4GC\SQLEXPRESS;Initial Catalog=autolab;Integrated Security=True";
        if (pn.CheckedItems.Count != 0)
        {
            // If so, loop through all checked items and print results.
            string s = "";
            int x;
            for (x = 0; x <= pn.CheckedItems.Count - 1; x++)
            {
                s = s + pn.CheckedItems[x].ToString();
            }
            connection.Open();
            SqlCommand cmd = new SqlCommand("SELECT *  from test_report  inner join tests  on test_report.test_name = tests.Test_name WHERE tests.Test_name IN ('" + s + "') ", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataTable tbl = new DataTable();

           adapter.Fill(tbl);

            dt.DataSource = tbl;

            connection.Close();

        }

Body:
It seems that your for loop concatenates list items. Try to write

s = s + pn.CheckedItems[x].ToString() + ", ";

Do not forget to remove last ", " after the loop.


问:
Remove ith item from a C++ std::vector
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

```<code>pList.remove(i);
</code>```

答:
Here is an O(1) solution, assuming you don't care about the order of elements:

```<code>#include <algorithm>

// ...

{
    using std::swap;
    swap(pList[i], pList.back());
    pList.pop_back();
}
</code>```

For PODs, assignment is faster than swapping, so you should simply write:

```<code>pList[i] = pList.back();
pList.pop_back();
</code>```

In C++11, you can forget the above distinction and always use move semantics for maximum efficiency:

```<code>if (i != pList.size() - 1)
{
    // Beware of move assignment to self
    // see http://stackoverflow.com/questions/13127455/
    pList[i] = std::move(pList.back());
}
pList.pop_back();
</code>```

Title: Remove ith item from a C++ std::vector

Body:
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i);

Body:
Here is an O(1) solution, assuming you don't care about the order of elements:

#include <algorithm>

// ...

{
    using std::swap;
    swap(pList[i], pList.back());
    pList.pop_back();
}

For PODs, assignment is faster than swapping, so you should simply write:

pList[i] = pList.back();
pList.pop_back();

In C++11, you can forget the above distinction and always use move semantics for maximum efficiency:

if (i != pList.size() - 1)
{
    // Beware of move assignment to self
    // see http://stackoverflow.com/questions/13127455/
    pList[i] = std::move(pList.back());
}
pList.pop_back();


问:
How do I print the image once I've stored it in a variable PHP
First of all, I'm a beginner in PHP. I'm trying to design a simple application to practice handling form elements. Basically, I upload an image, push submit, and then the image gets displayed in the web browser. The form works perfectly, but I'm having trouble displaying the image once I store it into a variable.

Does anybody know how to do this?

```<code><html>
<head>
<title>HI</title>
</head>
<body>

<form action = "blah.php" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "dope">
<input type = "submit" value = "Upload Images" name = "submit">
</form>

</body>
</html>
</code>```

The PHP file is:

```<code><?php

$image = $_FILES;
imagejpeg($image);
?>
</code>```

答:
You can simply get the mime type from the upload and read it back to the browser:

```<code>header('Content-Type: ' . $_FILES['dope']['type']);
readfile($_FILES['dope']['tmp_name']);
</code>```

This will send a header with the correct mime type so the browser knows how to handle it, if it's an image it'll be handled inline, if it's an application the browser will download it. readfile reads a file and sends it to directly to the buffer.

Be aware that if you want to store the file for future reads you will want to move it and store the location in a database or similar using move_uploaded_file, e.g.

```<code>move_uploaded_file($_FILES['dope']['tmp_name'], $destination);
</code>```

Then you can serve the file over and over providing $destination contains the file path:

```<code>header('Content-Type: ' . mime_content_type($destination));
readfile($destination);
</code>```

Body:
First of all, I'm a beginner in PHP. I'm trying to design a simple application to practice handling form elements. Basically, I upload an image, push submit, and then the image gets displayed in the web browser. The form works perfectly, but I'm having trouble displaying the image once I store it into a variable.

Does anybody know how to do this?

<title>HI</title>

<form action = "blah.php" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "dope">
<input type = "submit" value = "Upload Images" name = "submit">
</form>

The PHP file is:

<?php

$image = $_FILES;
imagejpeg($image);
?>

Body:
You can simply get the mime type from the upload and read it back to the browser:

header('Content-Type: ' . $_FILES['dope']['type']);
readfile($_FILES['dope']['tmp_name']);

This will send a header with the correct mime type so the browser knows how to handle it, if it's an image it'll be handled inline, if it's an application the browser will download it. readfile reads a file and sends it to directly to the buffer.

Be aware that if you want to store the file for future reads you will want to move it and store the location in a database or similar using move_uploaded_file, e.g.

move_uploaded_file($_FILES['dope']['tmp_name'], $destination);

Then you can serve the file over and over providing $destination contains the file path:

header('Content-Type: ' . mime_content_type($destination));
readfile($destination);


答:
The code has some mistakes.

```<code>for (int i = 0; i < list.size(); i++) {
        pq.add(list.remove());
}
</code>```

When you are copying the list in pq, you are using list.size() but you also remove the elements of the list in the loop. So you will not copy all the elements because the size will be decreasing.

Also, you are not implementing a priority queue, is just a copy of the list. In order to make a priority queue you have to insert the element in order. Then the min element will be at the top of queue (top is the first element of the list).

When you do that, you can do a pq.remove() in order to remove the min element.

Title: Removing min from LinkedList

Body:
I want to remove 3 from this list but I am not sure where to start. I am storing a sequence of numbers in a Priority Queue that implements a linked list and trying to locate the min and remove it from the priority queue using the removeMin method

import java.util.Iterator;
import java.util.LinkedList;
public class Test {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {

        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator it = pq.iterator();

        for (int i = 0; i < list.size(); i++) {
            pq.add(list.remove());
        }

        int min = pq.get(0);

        while (it.hasNext()) {
            // help here
        }

        return pq.remove();
    }

Body:
The code has some mistakes.

for (int i = 0; i < list.size(); i++) {
        pq.add(list.remove());
}

When you are copying the list in pq, you are using list.size() but you also remove the elements of the list in the loop. So you will not copy all the elements because the size will be decreasing.

Also, you are not implementing a priority queue, is just a copy of the list. In order to make a priority queue you have to insert the element in order. Then the min element will be at the top of queue (top is the first element of the list).

When you do that, you can do a pq.remove() in order to remove the min element.